AngularJS系列之JavaScript继承

来源:互联网 发布:网络ssid没有wlan 编辑:程序博客网 时间:2024/05/21 00:15

转载请注明来源:http://blog.csdn.net/caoshiying?viewmode=contents。这篇文章针对的是有2年以上编程经验的朋友们参考的,作参考资料之用,不从基础讲起。


所有开发者定义的类都可作为基类。本地类和宿主类不能作为基类。创建的子类将继承超类的所有属性和方法,包括构造函数及方法的实现。子类可直接访问这些方法。子类还可添加超类中没有的新属性和方法,也可以覆盖超类的属性和方法。

1.1.1.    对象冒充(object masquerading)

构造函数使用 this 关键字给所有属性和方法赋值(即采用类声明的构造函数方式)。因为构造函数只是一个函数,所以可使 ClassA 构造函数成为 ClassB 的方法,然后调用它。ClassB 就会收到 ClassA 的构造函数中定义的属性和方法。例如,用下面的方式定义 ClassA 和 ClassB:

function ClassA(sColor) {    this.color =sColor;    this.sayColor =function () {        alert(this.color);    };}function ClassB(sColor) {    this.newMethod =ClassA;    this.newMethod(sColor);    deletethis.newMethod;}


1.1.2.    call方法

 

call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身。

function sayColor(sPrefix,sSuffix) {    alert(sPrefix +this.color + sSuffix);};var obj = new Object();obj.color = "blue";sayColor.call(obj, "The color is", "a very nice color indeed.");


1.1.3.    apply方法

apply() 方法有两个参数,用作 this 的对象和要传递给函数的参数的数组。

function ClassB(sColor, sName) {    //this.newMethod =ClassA;    //this.newMethod(color);    //deletethis.newMethod;    ClassA.apply(this,new Array(sColor));     this.name = sName;    this.sayName =function () {        alert(this.name);    };}


同样的,第一个参数仍是this,第二个参数是只有一个值color 的数组。可以把 ClassB的整个 arguments 对象作为第二个参数传递给 apply() 方法

function ClassB(sColor, sName) {    //this.newMethod =ClassA;    //this.newMethod(color);    //deletethis.newMethod;    ClassA.apply(this,arguments);     this.name = sName;    this.sayName =function () {        alert(this.name);    };}


1.1.4.    原型链(prototype chaining)

这是针对函数字面量的方法。

prototype 对象是个模板,要实例化的对象都以这个模板为基础。总而言之,prototype 对象的任何属性和方法都被传递给那个类的所有实例。原型链利用这种功能来实现继承机制。

function ClassA() {}ClassA.prototype.color = "blue";ClassA.prototype.sayColor = function () {    alert(this.color);};function ClassB() {}ClassB.prototype = new ClassA();


1.1.5.    __proto__方法

这是针对对象字面量的方法。

var student1={    name:"李婷",    hobby:"羽毛球"};console.log(student1);var student2={    __proto__:student1,    age:22};console.log(student2.name+","+student2.hobby);


1.1.6.    混合方式

这种继承方式使用构造函数定义类,并非使用任何原型。对象冒充的主要问题是必须使用构造函数方式,这不是最好的选择。不过如果使用原型链,就无法使用带参数的构造函数了。

function ClassA(sColor) {    this.color =sColor;}ClassA.prototype.sayColor = function () {    alert(this.color);};function ClassB(sColor, sName) {    ClassA.call(this,sColor);    this.name = sName;}ClassB.prototype = new ClassA();ClassB.prototype.sayName = function () {    alert(this.name);};var objA = new ClassA("blue");var objB = new ClassB("red","John");objA.sayColor();  //输出 "blue"objB.sayColor();  //输出 "red"objB.sayName();   //输出 "John"


 

1 0
原创粉丝点击