标签:
1 理解Javascript constructor实现原理
在 JavaScript 中,每个函数都有名为“prototype”的属性,用于引用原型对象。此原型对象又有名为“constructor”的属性,它反过来引用函数本身。这是一种循环引用
2 JavaScript探秘:构造函数 Constructor
除了创建对象,构造函数(constructor) 还做了另一件有用的事情—自动为创建的新对象设置了原型对象(prototype object) 。原型对象存放于 ConstructorFunction.prototype 属性中。
1)原型链继承
function Parent(){
        this.name = ‘mike‘;
    }
    function Child(){
        this.age = 12;
    }
    Child.prototype = new Parent();//Child继承Parent,通过原型,形成链条
    var test = new Child();
    alert(test.age);
    alert(test.name);//得到被继承的属性
}
2)组合继承
   function Parent(age){
        this.name = [‘mike‘,‘jack‘,‘smith‘];
        this.age = age;
    }
    Parent.prototype.run = function () {
        return this.name  + ‘ are both‘ + this.age;
    };
    function Child(age){
        Parent.call(this,age);//对象冒充,给超类型传参
    }
    Child.prototype = new Parent();//原型链继承
    var test = new Child(21);//写new Parent(21)也行
    alert(test.run());//mike,jack,smith are both21
使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数复用,又保证每个实例都有它自己的属性。
一个系列文章,没有看完
标签:
原文地址:http://www.cnblogs.com/jinjin-blog/p/4757874.html