介绍:call与apply都属于Function.prototype的一个方法,所以每个function实例都有call、apply属性
// 有一个局部的test2方法,
// test2被作为普通函数调用时,
// test2内部的this指向了window,
// 但我们往往是想让它指向该#test节点,见如下代码:
document.querySelector("#test").onclick = function(){
console.log(this.id)
var test2 = function(){
console.log(this)
}
function test3(){
console.log(this)
}
test3.call(this)
//改变了test2的this指针
test2.call(this)
}
function one(){
this.a = 1,
this.b = 2,
this.test = function(){
// console.log(this)
}
}
//通过call来实现构造函数的继承
function two(){
one.call(this)
console.log(this)
}
// 实例化
var oneObj = new one()
twoObj = new two()
此时的twoObj已经继承了oneObj的属性。