ES5总结

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);//返回一个值,该值指示是否可向对象修改现有特性和值,添加新属性。

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

    原文作者:理想三旬7
    原文地址: https://www.jianshu.com/p/febf41a8dc13
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞