例子: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
复制代码