Convention for prototype inheritance in JavaScript

前端 未结 3 1873
挽巷
挽巷 2020-12-10 16:24

I see a lot of code like this:

function Base() {}
function Sub() {}
Sub.prototype = new Base();

However, if you do:

s = new         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-10 16:51

    Yeah,

    Sub.prototype.constructor = Sub;
    

    let's you use instanceof but there's a better solution. Look here: ,TDD JS Inheritance on GitHub ,and find the Parasitic Combination Inheritance pattern. The code is TDD'd so you should be able to grok it very quickly and then simply change the names to get you started. This is basically what YAHOO.lang.extend uses (source: yahoo employee and author Nicholas Zakas's Professional JavaScript for Web Developer's, 2nd ED, page 181). Good book by the way (not affiliated in any way!)

    Why? Because the classical pattern you're working with has staticy reference vars (if you create var arr = [1,2] in the base object, ALL instances will have read/write and will "share state" of 'arr'! If you use constructor stealing you can get around this. See my examples.

提交回复
热议问题