ES5總結(jié)

es5總結(jié)

xiong.jpg

1. strict模式

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

為什么使用嚴格模式:

  • 消除代碼運行的一些不安全之處,保證代碼運行的安全;

  • 消除Javascript語法的一些不合理、不嚴謹之處,減少一些怪異行為;

  • 提高編譯器效率,增加運行速度;

  • 為未來新版本的Javascript做好鋪墊。

"use strict";
 x = 3.14;   //報錯 不允許使用未聲明的變量或?qū)ο? ?
 "use strict";
 var x = 3.14;
 delete x;   //報錯 不允許刪除變量或?qū)ο蟆? ?
 "use strict";
 function x(p1, p2) {}; 
 delete x;  //報錯 不允許刪除函數(shù)。
 ?
 "use strict";
 function x(p1, p1) {};   // 報錯 不允許變量重名
 ?
 "use strict";
 var x = 010; // 報錯 不允許使用八進制
 ?
 "use strict";
 var x = \010; // 報錯 不允許使用轉(zhuǎn)義字符
 ?
 "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() 創(chuàng)建的變量不能被調(diào)用:
 ?
 禁止this關(guān)鍵字指向全局對象
 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回調(diào)支持3個參數(shù),第1個是遍歷的數(shù)組內(nèi)容;第2個是對應(yīng)的數(shù)組索引,第3個是數(shù)組本身

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方法的作用不難理解,“映射”嘛,也就是原數(shù)組被“映射”成對應(yīng)新數(shù)組。下面這個例子是數(shù)值項求平方:

遍歷數(shù)組,return返回組成一個新數(shù)組

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過濾掉數(shù)組不需要的元素,返回過濾后的新組數(shù),用法同map相似

filter的回調(diào)函數(shù)返回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() 方法用于檢測數(shù)組中的元素是否滿足指定條件(函數(shù)提供)。

some() 方法會依次執(zhí)行數(shù)組的每個元素:

如果有一個元素滿足條件,則表達式返回true , 剩余的元素不會再執(zhí)行檢測。 如果沒有滿足條件的元素,則返回false。

array.some(function(currentValue,index,arr),thisValue);
//第1個是遍歷的數(shù)組內(nèi)容;第2個是對應(yīng)的數(shù)組索引,第3個是數(shù)組本身 
//thisValue可選。對象作為該執(zhí)行回調(diào)時使用,傳遞給函數(shù),用作 "this" 的值。
如果省略了 thisValue ,"this" 的值為 "undefined"

every (js v1.6)

需要所有元素滿足條件

every() 方法用于檢測數(shù)組所有元素是否都符合指定條件(通過函數(shù)提供)。

every() 方法使用指定函數(shù)檢測數(shù)組中的所有元素:

  • 如果數(shù)組中檢測到有一個元素不滿足,則整個表達式返回 false ,且剩余的元素不會再進行檢測。

  • 如果所有元素都滿足條件,則返回 true。

array.every(function(currentValue,index,arr), thisValue);
  //第1個是遍歷的數(shù)組內(nèi)容;第2個是對應(yīng)的數(shù)組索引,第3個是數(shù)組本身 
  //thisValue可選。對象作為該執(zhí)行回調(diào)時使用,傳遞給函數(shù),用作 "this" 的值。
  如果省略了 thisValue ,"this" 的值為 "undefined"

indexOf (js v1.6)

用法:同字符串的indexOf一樣。 arr.indexOf(str,index);str:為索引的內(nèi)容,index為從第幾項開始找(包括這一項)

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

lastIndexOf (js v1.6)

lastIndexOf,同indexOf一樣,在數(shù)組末端開始找

arr.lastIndexOf(searchElement,Formindex);
從數(shù)組的末端開始找,F(xiàn)ormindex默認為arr.length-1,依次遞減

reduce (js v1.8)

遞歸。array.reduce(callback[, initialValue])

回調(diào)函數(shù)參數(shù)包括之前值、當(dāng)前值、索引值以及數(shù)組本身。initialValue參數(shù)可選,表示初始值。若指定,則當(dāng)作最初使用的previous值;如果缺省,則使用數(shù)組的第一個元素作為previous初始值,同時current往后排一位,相比有initialValue值少一次迭代。

注意: reduce() 對于空數(shù)組是不會執(zhí)行回調(diào)函數(shù)的。

var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
 return previous + current;
});
?
console.log(sum); // 10
// 初始設(shè)置
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() 從數(shù)組的末尾向前將數(shù)組中的數(shù)組項做累加。

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() 方法的主要作用就是將函數(shù)綁定至某個對象,bind()方法會創(chuàng)建一個函數(shù),函數(shù)體內(nèi)this對象的值會被綁定到傳入bind() 函數(shù)的值。

Function.prototype.bind =  function(context) {
 var self = this; // 保存原函數(shù)
 return function``() { // 返回一個新函數(shù)
 return self.apply(context, arguments); // 執(zhí)行新函數(shù)時,將傳入的上下文context作為新函數(shù)的this
 }
}
?
//實列
//1 實現(xiàn)對象繼承
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);
 }
};
// 事件處理函數(shù)綁定的錯誤方法:
document.querySelector('button')
 .addEventListener('click', paint.updateCount); // paint.updateCount函數(shù)的this指向變成了該DOM對象
// 事件處理函數(shù)綁定的正確方法:
document.querySelector('button')
 .addEventListener('click', paint.updateCount.bind(paint)); // paint.updateCount函數(shù)的this指向變成了paint
?
//3 時間間隔函數(shù)
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方法的區(qū)別

共同點:

都可以改變函數(shù)執(zhí)行的上下文環(huán)境;

不同點:

bind: 不立即執(zhí)行函數(shù),一般用在異步調(diào)用和事件; call/apply: 立即執(zhí)行函數(shù)。

call/apply上下文函數(shù)回顧

一般來說,this總是指向調(diào)用某個方法的對象,但是使用call()和apply()方法時,就會改變this的指向。

  • apply()方法

  • 定義:應(yīng)用某一個對象的一個方法,以另一個對象替換當(dāng)前對象 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()方法

  • 定義:應(yīng)用某一個對象的一個方法,以另一個對象替換當(dāng)前對象 call(this,arg1,arg2,...);

4.Date.now()

Date.now方法返回當(dāng)前時間距離時間零點(1970年1月1日 00:00:00 UTC)的毫秒數(shù),相當(dāng)于 Unix 時間戳乘以1000。es5新增

5.Object方法

Object.getPrototypeOf、Object.create

為了語法的規(guī)范性,用Object.setPrototypeOf()(寫操作)、Object.getPrototypeOf()(讀操作) 、Object.create()(生成操作)替換原來對象proto屬性

//Object.setPrototypeOf()(**寫操作**),用來設(shè)置一個對象的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()(**生成操作**) 第一個參數(shù)是要繼承的原型,如果不是一個子函數(shù),可以傳一個null,第二個參數(shù)是對象的屬性描述符,這個參數(shù)是可選的
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

返回對象所有屬性名稱,并添加到數(shù)組中

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

將屬性添加到對象,或修改現(xiàn)有屬性的特性

Object.defineProperty(object, propertyname, descriptor)

參數(shù)1,對象;參數(shù)2:屬性名;參數(shù)3:屬性內(nèi)容;

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

將一個或多個屬性添加到對象,并/或修改現(xiàn)有屬性的特性。

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

返回對象的可枚舉屬性和方法的名稱,返回的結(jié)果添加到一個新的數(shù)組中

// 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 阻止向?qū)ο筇砑有聦傩浴?/p>

// 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);//返回一個值,該值指示是否可向?qū)ο筇砑有聦傩浴?

Object.seal / Object.isSealed

Object.seal(object);阻止修改現(xiàn)有屬性的特性,并阻止添加新屬性。

  • 使對象不可擴展,這樣便無法向其添加新屬性。

  • 為對象的所有屬性將 configurable 特性設(shè)置為 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);//返回一個值,該值指示是否可向?qū)ο笮薷默F(xiàn)有屬性的特性,添加新屬性。

Object.freeze / Object.isFrozen

Object.freeze(object);阻止修改現(xiàn)有屬性的特性和值,并阻止添加新屬性。

  • 為對象的所有屬性將 configurable 特性設(shè)置為 false。在 configurablefalse 時,無法更改屬性的特性且無法刪除屬性。

  • 為對象的所有數(shù)據(jù)屬性將 writable 特性設(shè)置為 false。當(dāng) writable 為 false 時,無法更改數(shù)據(jù)屬性值。

// 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);//返回一個值,該值指示是否可向?qū)ο笮薷默F(xiàn)有特性和值,添加新屬性。

版權(quán):本文為信息資源整合,侵權(quán)即刪,歡迎轉(zhuǎn)載。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 概要 64學(xué)時 3.5學(xué)分 章節(jié)安排 電子商務(wù)網(wǎng)站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,789評論 0 3
  • 第2章 基本語法 2.1 概述 基本句法和變量 語句 JavaScript程序的執(zhí)行單位為行(line),也就是一...
    悟名先生閱讀 4,504評論 0 13
  • 第3章 基本概念 3.1 語法 3.2 關(guān)鍵字和保留字 3.3 變量 3.4 數(shù)據(jù)類型 5種簡單數(shù)據(jù)類型:Unde...
    RickCole閱讀 5,489評論 0 21
  • “關(guān)關(guān)雎鳩,在河之洲。” 下午,粽子依然,精彩繼續(xù)。池森外語,課堂內(nèi)外,卻不說外語,只包粽子。 又抓拍了幾張照片,...
    魯長安閱讀 732評論 0 0
  • 幸福其實是一種內(nèi)心的穩(wěn)定。我們沒有辦法決定外界的所有事情,但是我們可以決定自己內(nèi)心的狀態(tài)。
    池淺笑安然閱讀 240評論 0 0

友情鏈接更多精彩內(nèi)容