ES5总结

es5总结

xiong.jpg

1. strict模式

严格模式,限制一些用法,'use strict';

为什么使用严格模式:

  • 消除代码运行的一些不安全之处,保证代码运行的安全;

  • 消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;

  • 提高编译器效率,增加运行速度;

  • 为未来新版本的Javascript做好铺垫。

"use strict";
 x = 3.14;   //报错 不允许使用未声明的变量或对象
 ​
 "use strict";
 var x = 3.14;
 delete x;   //报错 不允许删除变量或对象。
 ​
 "use strict";
 function x(p1, p2) {}; 
 delete x;  //报错 不允许删除函数。
 ​
 "use strict";
 function x(p1, p1) {};   // 报错 不允许变量重名
 ​
 "use strict";
 var x = 010; // 报错 不允许使用八进制
 ​
 "use strict";
 var x = \010; // 报错 不允许使用转义字符
 ​
 "use strict";
 var obj = {};
 Object.defineProperty(obj, "x", {value:0, writable:false});
 obj.x = 3.14; // 报错 不允许对只读属性赋值
 ​
 "use strict";
 var obj = {get x() {return 0} };
 obj.x = 3.14;            // 报错 不允许对一个使用getter方法读取的属性进行赋值
 ​
 "use strict";
 delete Object.prototype; // 报错 不允许删除一个不允许删除的属性
 ​
 "use strict";
 var eval = 3.14;         // 报错 变量名不能使用 "eval" 字符串:
 ​
 "use strict";
 var arguments = 3.14;         // 报错 变量名不能使用 "arguments"  字符串:
 ​
 "use strict";
 with (Math){x = cos(2)}; // 报错 不允许使用with
 ​
 "use strict";
 eval ("var x = 2");
 alert (x);               // 报错 由于一些安全原因,在作用域 eval() 创建的变量不能被调用:
 ​
 禁止this关键字指向全局对象
 function f(){
  return !this;
 } 
 // 返回false,因为"this"指向全局对象,"!this"就是false
 ​
 function f(){ 
  "use strict";
  return !this;
 } 
 // 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。
 ​

2.Array增加方法

forEach (js v1.6)

forEach方法中的function回调支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身

var sum=0;
var arr=[1,2,3];
arr.forEach(function(value,i,arr){
 sum+=value;
 console.log(arr[i]==value)//true
});
console.log(sum);

map (js v1.6)

map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组。下面这个例子是数值项求平方:

遍历数组,return返回组成一个新数组

var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function (item) {
 return item * item
});
alert(arrayOfSquares); // 1, 4, 9, 16

filter (js v1.6)

过滤。刷选,filer过滤掉数组不需要的元素,返回过滤后的新组数,用法同map相似

filter的回调函数返回boolean为true的值

var arr=[1,3,4,5,0];
var arr2=arr.filter(function(item){
 return item;//为true则返回回去
})
//arr2=[1,3,4,5];
var arr2=arr.filter(function(item){
 return item=="3";
})

some (js v1.6)

只需一个满足条件

some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。

some() 方法会依次执行数组的每个元素:

如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。 如果没有满足条件的元素,则返回false。

array.some(function(currentValue,index,arr),thisValue);
//第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身 
//thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

every (js v1.6)

需要所有元素满足条件

every() 方法用于检测数组所有元素是否都符合指定条件(通过函数提供)。

every() 方法使用指定函数检测数组中的所有元素:

  • 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。

  • 如果所有元素都满足条件,则返回 true。

array.every(function(currentValue,index,arr), thisValue);
  //第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身 
  //thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
  如果省略了 thisValue ,"this" 的值为 "undefined"

indexOf (js v1.6)

用法:同字符串的indexOf一样。 arr.indexOf(str,index);str:为索引的内容,index为从第几项开始找(包括这一项)

arr.indexOf(4,2)//从索引是2的地方开始找,返回3,如果找不到就返回-1

lastIndexOf (js v1.6)

lastIndexOf,同indexOf一样,在数组末端开始找

arr.lastIndexOf(searchElement,Formindex);
从数组的末端开始找,Formindex默认为arr.length-1,依次递减

reduce (js v1.8)

递归。array.reduce(callback[, initialValue])

回调函数参数包括之前值、当前值、索引值以及数组本身。initialValue参数可选,表示初始值。若指定,则当作最初使用的previous值;如果缺省,则使用数组的第一个元素作为previous初始值,同时current往后排一位,相比有initialValue值少一次迭代。

注意: reduce() 对于空数组是不会执行回调函数的。

var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
 return previous + current;
});
​
console.log(sum); // 10
// 初始设置
previous = initialValue = 1, current = 2
​
// 第一次迭代
previous = (1 + 2) =  3, current = 3
​
// 第二次迭代
previous = (3 + 3) =  6, current = 4
​
// 第三次迭代
previous = (6 + 4) =  10, current = undefined (退出)

reduceRight (js v1.8)

reduceRight() 方法的功能和 reduce() 功能是一样的,不同的是 reduceRight() 从数组的末尾向前将数组中的数组项做累加。

var numbers = [2, 45, 30, 100];

function getSum(total, num) {
 return total - num;
}
function myFunction(item) {
 document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}

3.Function增加属性方法

Function.prototype.bind();

bind() 方法的主要作用就是将函数绑定至某个对象,bind()方法会创建一个函数,函数体内this对象的值会被绑定到传入bind() 函数的值。

Function.prototype.bind =  function(context) {
 var self = this; // 保存原函数
 return function``() { // 返回一个新函数
 return self.apply(context, arguments); // 执行新函数时,将传入的上下文context作为新函数的this
 }
}
​
//实列
//1 实现对象继承
var A = function(name) {
 this.name = name;
}
var B = function() {
 A.bind(this, arguments);
}
B.prototype.getName = function() {
 return this.name;
}
var b = new B("hello");
console.log(b.getName()); // "hello"
​
//2 事件处理
ar paint = {
 color: "red",
 count: 0,
 updateCount: function() {
 this.count++;
 console.log(this.count);
 }
};
// 事件处理函数绑定的错误方法:
document.querySelector('button')
 .addEventListener('click', paint.updateCount); // paint.updateCount函数的this指向变成了该DOM对象
// 事件处理函数绑定的正确方法:
document.querySelector('button')
 .addEventListener('click', paint.updateCount.bind(paint)); // paint.updateCount函数的this指向变成了paint
​
//3 时间间隔函数
var notify = {
 text: "Hello World!",
 beforeRender: function() {
 alert(this.text);
 },
 render: function() {
 // 错误方法:
 setTimeout(this.beforeRender, 0); // undefined
 // 正确方法:
 setTimeout(this.beforeRender.bind(this), 0); // "Hello World!"
 }
};
notify.render();
​
4 借用Array的原生方法
var a = {};
Array.prototype.push.bind(a, "hello", "world")();
console.log(a); // "hello", "world"

bind与 call/apply方法的区别

共同点:

都可以改变函数执行的上下文环境;

不同点:

bind: 不立即执行函数,一般用在异步调用和事件; call/apply: 立即执行函数。

call/apply上下文函数回顾

一般来说,this总是指向调用某个方法的对象,但是使用call()和apply()方法时,就会改变this的指向。

  • apply()方法

  • 定义:应用某一个对象的一个方法,以另一个对象替换当前对象 apply(this,arguments); apply(this,[arg1,arg2,...]);

var arr = [9,3,5,7,8,2];
 var max = Math.max.apply(null,arr);
console.log(max);
function fn(){
 var arr = [];
 arr.push.apply(arr1,arguments);
 return arr1;
}
//改变原来方法中的this指向,指向新的对象;
//例:改变了arr.push()中this的指向,指向到apply()中的arr1。call同理
  • call()方法

  • 定义:应用某一个对象的一个方法,以另一个对象替换当前对象 call(this,arg1,arg2,...);

4.Date.now()

Date.now方法返回当前时间距离时间零点(1970年1月1日 00:00:00 UTC)的毫秒数,相当于 Unix 时间戳乘以1000。es5新增

5.Object方法

Object.getPrototypeOf、Object.create

为了语法的规范性,用Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作) 、Object.create()(生成操作)替换原来对象proto属性

//Object.setPrototypeOf()(**写操作**),用来设置一个对象的prototype对象
let proto = {};
let obj = { x: 10 };
Object.setPrototypeOf(obj, proto);
​
//Object.getPrototypeOf()(**读操作**)
var rec = new Rectangle();
Object.getPrototypeOf(rec) === Rectangle.prototype
// true
​
//Object.create()(**生成操作**) 第一个参数是要继承的原型,如果不是一个子函数,可以传一个null,第二个参数是对象的属性描述符,这个参数是可选的
function Car (desc) {
 this.desc = desc;
 this.color = "red";
}
Car.prototype = {
 getInfo: function() {
 return 'A ' + this.color + ' ' + this.desc + '.';
 }
};
//instantiate object using the constructor function
var car =  Object.create(Car.prototype);
car.color = "blue";
alert(car.getInfo());

Object.getOwnPropertyNames

返回对象所有属性名称,并添加到数组中

function Pasta(grain, width, shape) {
 // Define properties.
 this.grain = grain;
 this.width = width;
 this.shape = shape;
 this.toString = function () {
 return (this.grain + ", " + this.width + ", " + this.shape);
 }
}
​
// Create an object.
var spaghetti = new Pasta("wheat", 0.2, "circle");
​
// Get the own property names.
var arr = Object.getOwnPropertyNames(spaghetti);
document.write (arr);
​
// Output:
//   grain,width,shape,toString

Object.defineProperty

将属性添加到对象,或修改现有属性的特性

Object.defineProperty(object, propertyname, descriptor)

参数1,对象;参数2:属性名;参数3:属性内容;

var newLine = "<br />";
// Create a user-defined object.
var obj = {};
// Add a data property to the object.
Object.defineProperty(obj, "newDataProperty", {
 value: 101,
 writable: true,
 enumerable: true,
 configurable: true
});
// Set the property value.
obj.newDataProperty = 102;
document.write("Property value: " + obj.newDataProperty + newLine);
​
// Output:
// Property value: 102

Object.getOwnPropertyDescriptor

获取指定对象的自身属性描述符。自身属性描述符是指直接在对象上定义(而非从对象的原型继承)的描述符。

非原型对象属性

Object.getOwnPropertyDescriptor(object, propertyname);
//实例
var obj = {};
// Add a data property.
obj.newDataProperty = "abc";
// Get the property descriptor.
var descriptor = Object.getOwnPropertyDescriptor(obj, "newDataProperty");

Object.defineProperties

将一个或多个属性添加到对象,并/或修改现有属性的特性。

object.defineProperties(object, descriptors)
//实例
var newLine = "<br />";
var obj = {};
Object.defineProperties(obj, {
 newDataProperty: {
 value: 101,
 writable: true,
 enumerable: true,
 configurable: true
 },
 newAccessorProperty: {
 set: function (x) {
 document.write("in property set accessor" + newLine);
 this.newaccpropvalue = x;
 },
 get: function () {
 document.write("in property get accessor" + newLine);
 return this.newaccpropvalue;
 },
 enumerable: true,
 configurable: true
 }});
​
// Set the accessor property value.
obj.newAccessorProperty = 10;
document.write ("newAccessorProperty value: " + obj.newAccessorProperty + newLine);
// Output:
// in property set accessor
// in property get accessor
// newAccessorProperty value: 10

Object.keys

返回对象的可枚举属性和方法的名称,返回的结果添加到一个新的数组中

// Create a constructor function.
function Pasta(grain, width, shape) {
 this.grain = grain;
 this.width = width;
 this.shape = shape;
​
 // Define a method.
 this.toString = function () {
 return (this.grain + ", " + this.width + ", " + this.shape);
 }
}
​
// Create an object.
var spaghetti = new Pasta("wheat", 0.2, "circle");
​
// Put the enumerable properties and methods of the object in an array.
var arr = Object.keys(spaghetti);
document.write (arr);
​
// Output:
// grain,width,shape,toString

Object.preventExtensions / Object.isExtensible

Object.preventExtensions 阻止向对象添加新属性。

// Create an object that has two properties.
var obj = { pasta: "spaghetti", length: 10 };
​
// Make the object non-extensible.
Object.preventExtensions(obj);
document.write(Object.isExtensible(obj));
document.write("<br/>");
​
// Try to add a new property, and then verify that it is not added.
obj.newProp = 50;
document.write(obj.newProp);
​
// Output:
// false
// undefined


Object.isExtensible(object);//返回一个值,该值指示是否可向对象添加新属性。

Object.seal / Object.isSealed

Object.seal(object);阻止修改现有属性的特性,并阻止添加新属性。

  • 使对象不可扩展,这样便无法向其添加新属性。

  • 为对象的所有属性将 configurable 特性设置为 false

// Create an object that has two properties.
var obj = { pasta: "spaghetti", length: 10 };
// Seal the object.
Object.seal(obj);
document.write(Object.isSealed(obj));
document.write("<br/>");
​
// Try to add a new property, and then verify that it is not added. 
obj.newProp = 50;
document.write(obj.newProp);
document.write("<br/>");
​
// Try to delete a property, and then verify that it is still present. 
delete obj.length;
document.write(obj.length);
​
// Output:
// true
// undefined
// 10

Object.isSealed(object);//返回一个值,该值指示是否可向对象修改现有属性的特性,添加新属性。

Object.freeze / Object.isFrozen

Object.freeze(object);阻止修改现有属性的特性和值,并阻止添加新属性。

  • 为对象的所有属性将 configurable 特性设置为 false。在 configurablefalse 时,无法更改属性的特性且无法删除属性。

  • 为对象的所有数据属性将 writable 特性设置为 false。当 writable 为 false 时,无法更改数据属性值。

// Create an object that has two properties.
var obj = { pasta: "spaghetti", length: 10 };
​
// Freeze the object.
Object.freeze(obj);
​
// Try to add a new property, and then verify that it is not added. 
 obj.newProp = 50;
 document.write(obj.newProp);
 document.write("<br/>");
​
// Try to delete a property, and then verify that it is still present. 
delete obj.length;
document.write(obj.length);
document.write("<br/>");
​
// Try to change a property value, and then verify that it is not changed. 
obj.pasta = "linguini";
document.write(obj.pasta);
​
// Output:
// undefined
// 10
// spaghetti

Object.isFreeze(object);//返回一个值,该值指示是否可向对象修改现有特性和值,添加新属性。

版权:本文为信息资源整合,侵权即删,欢迎转载。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 8,618评论 0 3
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,055评论 0 13
  • 第3章 基本概念 3.1 语法 3.2 关键字和保留字 3.3 变量 3.4 数据类型 5种简单数据类型:Unde...
    RickCole阅读 5,037评论 0 21
  • “关关雎鸠,在河之洲。” 下午,粽子依然,精彩继续。池森外语,课堂内外,却不说外语,只包粽子。 又抓拍了几张照片,...
    鲁长安阅读 628评论 0 0
  • 幸福其实是一种内心的稳定。我们没有办法决定外界的所有事情,但是我们可以决定自己内心的状态。
    池浅笑安然阅读 167评论 0 0