ES6 JavaScript call()函数的用法
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();