简体   繁体   中英

Error when calling function within array of its own prototype (js)

Sorry if this is a dumb question I'm just experimenting and don't understand why this doesn't work:

var MyFunc = function() {};                                                    

MyFunc.prototype = {                                                           
  receive: function() {                                                        
    console.log("Received");                                                   
  },                                                                           
  spine: [MyFunc],                                                             
}                                                                              

var func = new MyFunc();                                                       

func.receive();          //works                                               
func.spine[0].receive(); //error: Object function () {} has no method 'receive'

The last line is the error line.

Full output:

Received

/home/zxcv/Documents/CODE/js/stuff/gp/scratch.js:13
func.spine[0].receive(); //error: Object function () {} has no method 'receive
              ^
TypeError: Object function () {} has no method 'receive'
    at Object.<anonymous> (/home/USER/Documents/CODE/js/stuff/gp/scratch.js:13:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3

shell returned 8

Because spine[0] is MyFunc (the constructor function object), not an instance object of MyFunc. Functions defined in prototype get put on the instances created by the constructor not on the constructor itself.

You would have go through the prototype in order to execute the function

func.spine[0].prototype.receive();

If you were wanting to create a method that you could execute directly from MyFunc you would need to actually define it on MyFunc

MyFunc.receive2 = function(){
    console.log("Received");
};
var func = new MyFunc();
func.spine[0].receive2();
//Or
MyFunc.receive2();

//Note you would not be able to call this directly from the instance
func.receive2(); //would cause an error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM