关于JavaScript 中的继承 -- call, 和 apply

继续javascript 继承

Function.call()

将函数作为对象的方法调用

基本格式

function.call(thisobj, args...)

thisobj

调用 function 的对象。在函数主体中, thisobj 是关键字 this 的值。

args...

任意多的参数,这些参数将传递给函数 function 。

返回值

调用参数 function 的返回值

概念就是以上的了,写个实例看看咯

Example

1 function sayColor(sPrefix, sSuffix)

2 {

3 alert(sPrefix + this.color + sSuffix);

4 }

5

6 var obj = new obj();

7 obj.color = "red";

8 sayColor.call(obj, "thie color is", ", a very nice color!");

上面的 sayColor() 在对象外定义,但注意:即使它不属于任何对象,均可以引用关键字 this 。

最后会输出 the color is red, a very nice color!

现在看看如何实现继承

1 function classB(sColor, sName){

2 //this.newMethod = classA;

3 //this.newMethod(sColor);

4 //delete this.newMethod;

5 classA.call(this, sColor);

6

7 this.name = sName;

8 this.sayName = function(){

9 alert(this.name);

10 }

11 }

好了 现在看看 Function.apply()

function.apply(thisobj, args)

thisobj

调用 function 的对象。在函数主体中,thisobj 是关键字 this 的值

args

一个数组,它的元素是要传递给函数 function 的参数值。

返回值

调用函数 function 的返回值

描述

apply() 将指定的函数 function 最为对象 thisobj 的方法来调用, 传递给它的是存放在数组 args 中的参数,返回的是调用 function 的返回值。在函数体内,关键字 this 引用 thisobj 对象

简洁点

1 function sayColor(sPrefix, sSuffix){

2 alert(sPrefix + this.color + sSuffix);

3 };

4

5 var obj = new Object();

6 obj.color = "red";

7

8 // 输出 "the color is red, a very nice color."

9 sayColor.apply(obj, new Array("the color is ",", a very nice color."));

注意: apply 的 args 参数为数组 new Array("the color is", ", a very nice color.");

只有超类中的参数顺序与子类中的参数顺序完全一致时才可以传递参数对象。

如果不是,就必须创建一个单独的数组,按照正确的顺序放置参数。此外还可以使用 call 方法