js中,call()函數用於改變this的指向
在function.call(target)中,function調用call時,function中的this會改變為指向target。以下幾個例子將體會call的用法
1.target調用其他對象的方法
下例中 代碼cat1.say.call(dog2) 將say方法中的this臨時由cat1改為了dog2
function cat(){ } //原型擴展 cat.prototype={ food:"fish", say: function(){ alert("I love "+this.food); } } var cat1 = new cat(); cat1.say();//I love fish //當我需要一條狗也說它喜歡什么時,可以定義say方法,也可以通過call用cat1的say方法,如下 dog2 = {food:"bone"}; cat1.say.call(dog2);//I love bone
2.方法替換
function NameShowing(){ this.showName = function(){ document.write(this.name); //此行this將被target替換 } } function Person(name){ this.name = name; }; var nameShowing = new NameShowing(); var jeremy = new Person("Jeremys") //此時nameShowing被當做function的實例,showName中的this被指向jeremy,輸出Jeremys nameShowing.showName.call(jeremy);
3.對象替換
function NameShowing(){ this.showName = function(){//此行的this將被target替代 document.write(this.name); } } function Person(name){ this.name = name; }; var jeremy = new Person("Jeremys"); //call將NameShowing的this指向jeremy,相當於執行了jeremy.showName=function(){document.write(this.name);}使得jeremy實例擁有了showName方法 NameShowing.call(jeremy); jeremy.showName();//輸出Jeremys
4.構造函數
function Person(name, age){ this.name = name; this.age = age; this.showPersonInfo = function(){ document.write("Name: " + this.name + ""); document.write("Age: " + this.age + ""); }; } var jeremy = new Object(); Person.call(jeremy, "Jeremy", 20); //相當於將Person函數中的this替換為jeremy,並執行一遍Person函數 //function Person(obj, name, age){ // obj.name = name; // obj.age = age; // obj.showPersonInfo = function(){ // document.write("Name: " + this.name + ""); // document.write("Age: " + this.age + ""); // }; //} //Person(jeremy, "Jeremy", 20); jeremy.showPersonInfo();