Heim  >  Artikel  >  Web-Frontend  >  JavaScript 学习笔记(九)call和apply方法_基础知识

JavaScript 学习笔记(九)call和apply方法_基础知识

WBOY
WBOYOriginal
2016-05-16 18:36:45695Durchsuche
call和apply方法
call方法可改变上下文this指针,类似的方法还有apply,主要用在js对象各方法互相调用的时候,使当前this实例指针保持一致,或在特殊情况下需要改变this指针。
obj1.method1.call(obj2,argument1,argument2)
如上,call的作用就是把obj1的方法放到obj2上使用,后面的argument1…这些做为参数传入。
举一个具体的例子
复制代码 代码如下:

function add(a, b) {
alert(a + b);
}
function sub(a, b) {
alert(a - b);
}
add.call(sub, 3, 1);

这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4); // 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。
看一个稍微复杂一点的例子
复制代码 代码如下:

function Class1() {
this.name = "class1";

this.showNam = function() {
alert(this.name);
}
}

function Class2() {
this.name = "class2";
}

var c1 = new Class1();
var c2 = new Class2();

c1.showNam.call(c2);

注意,call 的意思是把 c1 的方法放到c2上执行,原来c2是没有showNam() 方法,现在是把c1 的showNam()方法放到 c2 上来执行,所以this.name 应该是 class2,执行的结果就是:alert("class2");
另外可以用 call 来实现继承
复制代码 代码如下:

function Class1() {
this.showTxt = function(txt) {
alert(txt);
}
}

function Class2() {
Class1.call(this);
}

var c2 = new Class2();

c2.showTxt("cc");

这样 Class2 就继承Class1了,Class1.call(this) 的 意思就是使用 Class1 对象代替this对象,那么 Class2 中不就有Class1 的所有属性和方法了吗,c2 对象就能够直接调用Class1 的方法以及属性了,执行结果就是:alert(“cc”);
这就是 javaScript 如何来模拟面向对象中的继承的,还可以实现多重继承。
复制代码 代码如下:

function Class10() {
this.showSub = function(a, b) {
alert(a - b);
}
}

function Class11() {
this.showAdd = function(a, b) {
alert(a + b);
}
}

function Class2() {
Class10.call(this);
Class11.call(this);
}

1.call方法
调用一个对象的一个方法,以另一个对象替换当前对象。
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
参数
thisObj 可选项。将被用作当前对象的对象。
arg1, arg2, , argN 可选项。将被传递方法参数序列。
2.apply方法
应用某一对象的一个方法,用另一个对象替换当前对象。
apply([thisObj[,argArray]])
参数
thisObj 可选项。将被用作当前对象的对象。
argArray 可选项。将被传递给该函数的参数数组。

两者的区别
两者实现的功能是完全一样的,只是参数传递方式不一样,call是将各个参数以逗号(,)隔开,而apply是将所有参数组成一个数组进行传递。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn