js中call和apply的用法
通俗的講,apply和call就是為了改變函數體內部this的指向.
1.call()方法
用法:
<1> obj.call(thisObj,arg1,arg2,...)
把obj(this)綁定到thisObj,這個時候thisObj具備了obj的屬性和方法,或者說thisObj繼承了obj的屬性和方法.
2.apply()方法:
用法:
<1>obj.apply(thisObj,[arg1,arg2,...])
把obj(this)綁定到thisObj,這個時候thisObj具備了obj的屬性和方法,或者說thisObj繼承了obj的屬性和方法.
區別:apply接受的是數組參數,call接受的是連續參數.
//1.實現繼承:
var Parent = function () {
this.name = "mayun";
this.age = 18;
}
var child = {};
console.log(child) //打印結果: {}
Parent.call(child)
console.log(child)//打印結果: {name:"mayun",age:18}
//2.劫持別人的方法:
var test1 = {
name:"test1",
showName: function () {
console.log(this.name)
}
}
var test2 = {
name:"test2"
};
test1.showName.call(test2) //打印結果:test2
//此時showName中的this指針指向了test2,this.name就是test2.name
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。