简体   繁体   中英

How to call a prototype from parent js

Uncaught TypeError: this.rnd is not a function.

What to do in this case? I understand that you need to use the call method somehow?

 var foo = function () { var write = function () { document.write(this.rnd([1, 3, 5, 7])); } write(); } foo.prototype.rnd = function(array) { return array[Math.round(Math.random() * (array.length - 1))]; } var f = new foo(); 

 var foo = function(){ var write = function(ctx) { document.write(ctx.rnd([1, 3, 5, 7])); } write(this); } foo.prototype.rnd = function(array) { return array[Math.round(Math.random() * (array.length - 1))]; } var f = new foo() 

If you want to set it up this way you could define write on the instance so you can call it with this.write() . Each instance would have its own copy of the function, which is often unnecessary:

 var foo = function(){ this.write = function() { console.log(this.rnd([1, 3, 5, 7])); } this.write(); } foo.prototype.rnd = function(array){ return array[Math.round(Math.random() * (array.length - 1))]; } var f = new foo(); 

Alternatively, you could put write() on the prototype as well, then all instances would share the same function:

 var foo = function(){ this.write(); } foo.prototype.write = function() { console.log(this.rnd([1, 3, 5, 7])); } foo.prototype.rnd = function(array){ return array[Math.round(Math.random() * (array.length - 1))]; } var f = new foo(); 

If you wanted to use call() you could do it like this which would manually bind this inside write() to the instance :

 var foo = function () { var write = function () { console.log(this.rnd([1, 3, 5, 7])); } write.call(this); } foo.prototype.rnd = function(array) { return array[Math.round(Math.random() * (array.length - 1))]; } var f = new foo(); 

You have a problem there with the scope , of the this . The code below would work

var foo = function(){   
    var currentThis = this
    var write = function() {
        document.write(currentThis.rnd([1, 3, 5, 7]));

    }
    write();
}


foo.prototype.rnd = function(array)
{

return array[Math.round(Math.random() * (array.length - 1))];

}


var f = new foo();

The problem here is that by the time you got to the write, the this was not the same this as the one for the foo constructor. As you learn vanilla javascript you might find people doing also

var self = this
var that = this

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