How to “properly” create a custom object in JavaScript?

后端 未结 15 1982
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  情话喂你
    2020-11-21 08:30

    Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:

    var mammal = function (spec) {     
       var that = {}; 
       that.get_name = function (  ) { 
          return spec.name; 
       }; 
       that.says = function (  ) { 
          return spec.saying || ''; 
       }; 
       return that; 
    }; 
    
    var myMammal = mammal({name: 'Herb'});
    

    In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:

    function Person() {
       this.name = "John";
       return this;
    }
    
    var person = new Person();
    alert("name: " + person.name);**
    

    In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.

提交回复
热议问题