开发者

function MyClass(){ ... }; MyClass.prototype = MyClass; -- considered harmful?

开发者 https://www.devze.com 2023-01-24 20:06 出处:网络
Apparently it is an idiom in JavaScript to implement class based instance methods this way: function MyClass(){...}

Apparently it is an idiom in JavaScript to implement class based instance methods this way:

function MyClass(){...}
MyClass.prototype.methodA = function(){...}
MyClass.prototype.methodB = function(){...}
...

Why aren't people using this less verbose form instead:

function MyClass(){...}
MyClass.prototype = MyClass;
MyClass.methodA = function(){...}
MyClass.methodB = function(){...}

It obviously does not work if MyClass should inherit from some base class (in that case one should set the prototype to a new instance of the base class typically).

开发者_StackOverflow社区

However, deep inheritance hierachies are getting rare these days (thanks to duck typing and mixins among other things).

Am I missing something?

Does MyClass.prototype = MyClass makes .constuctor more a mess than it is already?

Does it interferes in bad ways with typeof, or instanceof, or even getPrototypeOf()?

Should it be promoted, or considered harmful?


Maybe because there's an even less verbose form?

MyClass.prototype = {
    methodA: function(){},
    methodB: function(){}
};

This gets cleaner the more methods you have, other than that, you're just overriding the default prototype and whatever was on it.


I think it's pointless, and it sets you up for potential trouble if one of your methods has a name that obscures a native method from Function.prototype.

You can always initialize the prototype like this:

function MyConstructor() { ... }

MyConstructor.prototype = {
  myMethod: function() { ... },
  whatever: null
};

edit — if you don't like creating object constants (and I have to say that if you're going to be coding in Javascript a lot, I suggest that you try to get used to them), you can just do this:

MyConstructor.prototype = {};
MyConstructor.prototype.myMethod = function() { ... };

I don't like doing that much typing, personally.

0

精彩评论

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