例子:bash
//綁定指向
var obj3 = {}
var login = function(){
return this;
};
console.log(login() === window); //true
console.log(login.call(obj3) === obj3); //true
複製代碼
例子二:ui
var n = 123;
var obj = {
n: 456
};
function a() {
console.log(this.n);
}
a.call() // 123
a.call(null) // 123
a.call(undefined) // 123
a.call(window) // 123
a.call(obj) // 456
複製代碼
解析:this
var f = function () {
return this;
};
f.call(5)
// Number {[[PrimitiveValue]]: 5}
複製代碼
function add(a, b) {
return a + b;
}
add.call(this, 1, 2) // 3
複製代碼
var obj5 = {}
alert(obj5.hasOwnProperty('toString')); //false
obj5.hasOwnProperty = ()=>{
return true;
}
console.log(obj5.hasOwnProperty('toString')); //true
console.log(Object.prototype.hasOwnProperty.call(obj5,'toString')) //false
複製代碼