Adding a prototype to an object literal

后端 未结 3 1413
慢半拍i
慢半拍i 2020-12-09 13:09

I have some object, say son, which I\'d like to inherit from another object father.

Of course I can make a constructor function for father,

3条回答
  •  一生所求
    2020-12-09 14:07

    That's incorrect jmar777. If for example you have

    var X = function() {};
    X.prototype = {
      protoFunc1: function() { console.log('p1');},
      protoFunc2: function() { console.log('p2');}
    };
    
    X.protoFunc1(); // is not a function 
    

    That means that what you're doing:

    X.prototype = {}
    

    is just creating an object called prototype. Not the actual prototype. To use prototype you have to use constructor functions.

    if however you modify it to this (constructor method)

    function X(){};
    X.prototype.protoFunc1 = function() { 
        console.log('p1');
    }
    X.prototype.protoFunc2 = function() { 
        console.log('p2');
    }
    
    var x = new X();
    x.protoFunc1(); //'p1'
    

    It would work.

    Either go the object literal method without using prototype or use the contructor method using prototype.

提交回复
热议问题