1.比較兩個對象是否相等
function isEqual(a, b) {
var aProps = Object.getOwnPropertyNames(a),
bProps = Object.getOwnPropertyNames(b);
//1.先比較屬性的個數(shù)是否相等
if (aProps.length != bProps.length) {
return false;
}
//2.屬性個數(shù)相等,再比較每個屬性的值是否相等
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
2.bind、call、apply
-
bind
:Function.prototype.bind(context),用于在不調(diào)用函數(shù)的情況下,將this固定在context上,并返回一個有新的this
值的函數(shù)。
用法:
var moneyGorden = {
name:"gorden",
money:1000,
addMoney:function (x) {
this.money += x;
console.log(this.name+" has "+this.money) ;
}
};
var moneyJack = {
name:"jack",
money:100
};
//直接調(diào)用
moneyGorden.addMoney(100);//gorden has 1100
//使用bind
var newFuntionUseBind = moneyGorden.addMoney.bind(moneyJack);
newFuntionUseBind(100);//jack has 200
//可以看到bind返回的是一個新函數(shù),原函數(shù)不受影響
moneyGorden.addMoney(100);//gorden has 1200
call
、apply
: 與bind
不同的是,這兩個方法直接修改函數(shù)運行時的this
值,并且可以給運行的函數(shù)傳遞參數(shù),以參數(shù)列表的形式跟在context后面。他們兩的不同在于參數(shù)傳遞,call
跟一個參數(shù)列表,將參數(shù)全部列出來,而apply
跟一個參數(shù)數(shù)組。可以記憶為 apply、array都以"a"開頭,所以apply跟一個array。重寫bind方法
Function.prototype.bind = Function.prototype.bind || function(context){
var self = this;
return function(){
return self.apply(context, arguments);
};
}
3. this值的總結(jié) 原文在這里
- 在全局作用域或者一個匿名函數(shù)中,
this
指向window
對象 - 嚴格模式下,在一個立即執(zhí)行函數(shù)(IIFE)中
this
是undifined
,需要將window
作為參數(shù)傳入。 - 當在一個對象的環(huán)境(context)中執(zhí)行函數(shù)市,
this
的值就指向這個對象 - 在
setTimeOut
中,this
指向全局對象 - 使用構(gòu)造函數(shù)創(chuàng)建一個對象時(使用
new
關(guān)鍵字),this指向這個新創(chuàng)建的對象 - 使用
bind
、cal
l、apply
指定this的值 - 在dom事件處理的handler中,
this
指向觸發(fā)事件的元素