javascript inheritance

后端 未结 5 1895
长情又很酷
长情又很酷 2020-12-05 21:29

I know there is a lot of similar questions are tons of great answers to this. I tried to look at the classical inheritance methods, or those closure methods etc. Somehow I c

5条回答
  •  庸人自扰
    2020-12-05 21:54

    Just thought I'd mention some of the issues with the classical pattern you're going for:

    1. Reference vars on the super class(es) will be available as essentially statics on ALL instances. For example, if you have var arr = [1,2,3] in the super, and do instance_1.arr.push(4) instance_2.arr.push(5) ALL of these instances will "see" the changes.
    2. So you solve 1. with Ayman's solution which Zakas calls "Constructor Stealing", but now you call the constructor twice: once for your prototype and once for the constructor stealing. Solution - for your prototype use a helper like inheritPrototype (I showed the whole implementation of this in this post: inheritPrototype method FWIW, this essentially came from a combination of page 181 of Zakas's book and some Crockford study.

    3. No privacy (but then again, you'd need to use something like the Durable Object pattern to get this and that may not be what you want)

    4. Object definition is left "dangling": Solution - put an if statement checking for any of your prototype's functions and then define the prototype with a prototype literal.

    I have running examples of all of this on github!!!

    It's been just as much of a challenge for me to truly grok both: Zakas and Crockford books on object creation and inheritance. I also needed to try some different JavaScript TDD frameworks. So I decided to create an essay on both TDD Frameworks and JavaScript Object Creation & Inheritance. It has running code and jspec tests! Here's the link:* My GitHub Open Source Essay/Book

提交回复
热议问题