Object creation mode

  • Object constructor pattern
    var obj = {};
    obj.name = 'Tom'
    obj.setName = function(name){this.name=name}
    Copy the code
  • Object literal schema
    var obj = {
      name : 'Tom',
      setName : function(name){this.name = name}
    }
    Copy the code
  • Constructor pattern
    function Person(name, age) { this.name = name; this.age = age; this.setName = function(name){this.name=name; }; } new Person('tom', 12);Copy the code
  • Constructor + prototype combined pattern
    function Person(name, age) { this.name = name; this.age = age; } Person.prototype.setName = function(name){this.name=name; }; New Person(' Tom ', 12);Copy the code

Inheritance mode

  • Prototype chain inheritance: get method

    function Parent(){} Parent.prototype.test = function(){}; function Child(){} Child.prototype = new Parent(); / / a subtype of prototype to Child. The parent type instance prototype. The Child var Child constructor = = new Child (); / / a test ()Copy the code
    Child.prototype.constructor = Child
    Copy the code

    Note: This statement modifies the correct constructor, as shown below

    Function Parent() {} function Child() {} function Child() {} / / constructor property is only exists in the prototype of the object attributes in the instance objects, point to the object instance constructor Child. The prototype. The constructor = Child; var child = new Child(); var p2=new Parent(); console.log(p2==Child.prototype); //false, p2 is not related to the prototype of the child instance object! console.log(p2.constructor); //Parent console.log(Child.prototype.constructor); //Child console.log(child.constructor); //ChildCopy the code
  • Borrow constructors: get properties (using no inheritance, this is a fake inheritance method)

    function Parent(xxx){this.xxx = xxx} Parent.prototype.test = function(){}; function Child(xxx,yyy){ Parent.call(this, xxx); This.parent (XXX)} var child = new child ('a', 'b'); //child. XXX is 'a', but child does not test()Copy the code
  • combination

    function Parent(xxx){this.xxx = xxx} Parent.prototype.test = function(){}; function Child(xxx,yyy){ Parent.call(this, xxx); Constructor this.parent (XXX)} Child. Prototype = new Parent(); Test () var child = new child (); //child. XXX = 'a', also test()Copy the code
  • What does new do behind an object?

    • Create an empty object
    • Set __proto__ to the constructor object’s prototype property value this.proto = fn. prototype
    • Execute the constructor body (add attributes/methods to the object)