JS 继 承 方 式

来源:互联网 发布:手机淘宝返利怎么关闭 编辑:程序博客网 时间:2024/04/27 16:07

JS

JS的继承主要通过四种途径实现:

1、          对象冒充(Object Masquerading

以下为实现对象冒充的js代码,定义了一个函数ClassA

 

定义了函数ClassB,并且将ClassA赋值给newMethod,并将sColor参数做为ClassA函数的参数。

 

2、          CallsubObject,parentFuncArgu1…. ParentFuncArguN)方法

subObject:子类对象

parentFuncArgu1:父类的第一个参数

parentFuncArguN:父类的第N个参数

         使用方法如下:

        

3、          apply()方法

The apply() method takes two arguments: the object to be used for this and an array of arguments to be passed to the function.apply方法接收两个参数,第一个是this对象,第二个是传递到函数的数组对象。)

你也可以讲ClassB的整个参数对象作为apply()函数第二个参数。

 

4、          原型prototype方法(Prototype chaining

      

运行下面的代码测试继承关系是否正确:

var objA = new ClassA();

var objB = new ClassB();

objA.color = red;

objB.color = blue;

objB.name = Nicholas;

objA.sayColor(); //outputs red

objB.sayColor(); //outputs blue

objB.sayName(); //outputs Nicholas

 

 

原创粉丝点击