日期:2014-05-16  浏览次数:20411 次

彻底理解javascript继承机制及call(),apply()方法的使用

?? ? ?关于javascript中call()和apply()方法的使用,网上有一博友已经写得非常清楚,链接地址如下:

关于JavaScript中apply与call的用法意义及区别

?

?在了解了javascript中call和apply方法的使用方法之后,下面具体讲一下继承的实现方式:

<html>
<head>
<title></title>
</head>
<body>

<script language="javascript" type="text/javascript">
    function ClassParent(name){
        this.name = name;
        this.sayName = function(){
            alert(this.name);
        }
    }
   //一‘对象冒充 
    function ClassChild(name,sex){
        this.newMethod = ClassParent;//函数名指针指向ClassParent;
        this.newMethod(name);//调用该方法。
        delete this.newMethod;//删除对ClassParent的引用,这样以后就不能再调用它了。
        this.sex = sex;
        this.saySex= function(){
            alert(this.sex);    
        }
    }    
    var obj = new ClassChild("jesen","nan");
    obj.saySex();
    obj.sayName();  
   //二、call()方法
    function ClassChild2(name,sex){
        ClassParent.call(this,name);
        this.sex=sex;
        this.saySex = function(){
            alert(this.sex);
        }
    }
    var obj2 = new ClassChild2("jesen2","nan2");
    obj2.saySex();
    obj2.sayName();
   //三、apply()方法
   function ClassChild3(name,sex){
        ClassParent.apply(this,new Array(name));
   //ClassParent.apply(this,arguments);此处可以使用参数对象arguments,当然只有是在超类中的参数顺序与子类中的参数顺序完全一致时才适用。
        this.sex=sex;
        this.saySex = function(){
            alert(this.sex);
        }
    } 
    var obj3 = new ClassChild2("jesen3","nan3");
    obj3.saySex();
    obj3.sayName(); 
    //四、原型链
    function ClassPrototypeParent(){
    }
    ClassPrototypeParent.prototype.name="jesen4";
    ClassPrototypeParent.prototype.sayName=function (){
        alert(this.name);
    }
    function ClassPrototypeChild(){
    }
    ClassPrototypeChild.prototype = new ClassPrototypeParent();//原型链必须确保构造函数没有任何参数。
    ClassPrototypeChild.prototype.name="jesen4child";
    ClassPrototypeChild.prototype.sex="nan4child";
    ClassPrototypeChild.prototype.saySex=function(){
        alert(this.sex);
    }
    var objp = new ClassPrototypeParent();
    var objc = new ClassPrototypeChild();
    objp.sayName();
    objc.sayName();
    objc.saySex();
    //五、混合方式
    //javascript创建类得最好的方法是用构造函数定义属性,用原型方式定义方法。
</script>
</body>

</html>

???

JavaScript中有一个call和apply方法,其作用基本相同,但也有略微的区别。

先来看看JS手册中对call的解释:

call 方法
调用一个对象的一个方法,以另一个对象替换当前对象。

call([thisObj[,arg1[, arg2[,?? [,.argN]]]]])

参数
thisObj
可选项。将被用作当前对象的对象。

arg1, arg2,??, argN
可选项。将被传递方法参数序列。

说明
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

说明白一点其实就是更改对象的内部指针,即改变对象的this指向的内容。这在面向对象的js编程过程中有时是很有用的。

引用网上一个代码段,运行后自然就明白其道理。