开发者

Constructors and inheritance in JavaScript

开发者 https://www.devze.com 2022-12-23 06:14 出处:网络
This is about \"inheritance\" in JavaScript. Suppose I create a constructor Bird(), and another called Parrot() which I make to \"inherit\" the properties of Bird by assigning an instance of it to Pa

This is about "inheritance" in JavaScript.

Suppose I create a constructor Bird(), and another called Parrot() which I make to "inherit" the properties of Bird by assigning an instance of it to Parrot's prototype, like the following code shows:

function Bird() {
    this.fly = function(){};
}

function Parrot() {
    this.talk = function(){ alert("praa!!"); };
}
Parrot.prototype = new Bird();

var p = new Parrot();

p.talk(); // Alerts "praa!!"
alert(p.constructor); // Alerts the Bird function!?!?!

After I've created an instance of Parrot, why is the .co开发者_Go百科nstructor property of it Bird(), and not Parrot(), which is the constructor I've used to create the object?


Prototype is an object just like anything else in JavaScript and object assignments are by reference. You just assigned a new bird to parrot's prototype so parrot's prototype is now a bird instance. And a bird's constructor is Bird.

You could fix this with the line

Parrot.prototype.constructor = Parrot;

Another way to do this would be to assign a clone of Bird's prototype to Parrot.prototype

function deepClone(obj) {
    var clone = {};
    for(var i in obj) {
        if(typeof(obj[i])==="object") {
            clone[i] = deepClone(obj[i]);
        } else {
            clone[i] = obj[i];
        }
    }
    return clone;
}


Parrot.prototype = deepClone(Bird.prototype);
Parrot.prototype.constructor = Parrot;

I prefer this because:

1) it saves creating an arbitrary instance of bird (what if something is counting hwo many birds have been created)

2) What if Bird constructor took an argument which was tested in the constructor body? Then calling:

Parrot.prototype = new Bird();

could then cause a null pointer


The constructor refers to the function that creates an instance's prototype (rather than the instance).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号