开发者

Inherit from Parent Class via $.extend

What are the differences between the 2 following approaches for inheritance?

Subclass.prototype = $.extend(true, {}, Parent.prototype, proto);

and

function Subclass(){
    var parent = new Parent();
    $.extend(true, this, parent);
}

Pros 开发者_StackOverflowand cons of each approach?

Thanks!

EDIT: I'm currently using the 1st approach to extend my classes, but I'm thinking of instantiating a parent object instead, so that the constructor of the Parent class gets called. Although I'm not convinced I'd always want that...


The major difference is in the second example, new Parent(), you are actually calling Parent and creating a new object which could cause unintended problems.

Using $.extend with the prototype like the first example, no code is going to be run. jQuery will look at the prototypes and extend the object for you and there won't be the possible side effects of running Parent()

There is no way I can explain it as well as this guy who has the top answer: How to "properly" create a custom object in JavaScript?

Here is a quote from the linked answer

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜