What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1478
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  心在旅途
    2020-11-22 07:47

    Because I will not admit the YUI/Crockford factory plan and because I like to keep things self contained and extensible this is my variation:

    function Person(params)
    {
      this.name = params.name || defaultnamevalue;
      this.role = params.role || defaultrolevalue;
    
      if(typeof(this.speak)=='undefined') //guarantees one time prototyping
      {
        Person.prototype.speak = function() {/* do whatever */};
      }
    }
    
    var Robert = new Person({name:'Bob'});
    

    where ideally the typeof test is on something like the first method prototyped

提交回复
热议问题