开发者

Using `this` in Crockford's pseudoclassical inheritance pattern

开发者 https://www.devze.com 2022-12-31 23:27 出处:网络
I\'ve just read The Good Parts, and I\'m slightly confused about something. Crockford\'s example of pseudoclassical inheritance goes like this:

I've just read The Good Parts, and I'm slightly confused about something. Crockford's example of pseudoclassical inheritance goes like this:

var Mammal = function (name) {
    this.name = name;
};

Mammal.prototype.ge开发者_开发百科t_name = function () {
    return this.name;
};

Part of the problem with this is that the constructor has "its guts hanging out" - the methods are outside of the constructor function. I don't see what's wrong with assigning get_name to this inside the constructor though. Is it because we'd end up with multiple copies of the get_name method?


Yes, that's basically it.

By assigning them to the prototype, they will be inherited by all instances of Mammal: there will only be one single copy of those functions in the entire system, no matter how many Mammals there are.

0

精彩评论

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