简体   繁体   English

如何从父级js调用原型

[英]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? 我了解您需要以某种方式使用call方法?

 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() . 如果要通过这种方式进行设置,则可以在实例上定义write ,以便可以使用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: 另外,您也可以将write()放在原型上,然后所有实例将共享相同的功能:

 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 : 如果你使用call() ,你可以做这样这将手动绑定this里面write()的实例:

 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. 这里的问题是,到您写这篇文章的时候,这和foo构造函数的代码已经不一样了。 As you learn vanilla javascript you might find people doing also 当您学习香草javascript时,您可能会发现人们也在做

var self = this
var that = this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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