簡體   English   中英

如何從父級js調用原型

[英]How to call a prototype from parent js

Uncaught TypeError: this.rnd is not a function.

在這種情況下該怎么辦? 我了解您需要以某種方式使用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() 

如果要通過這種方式進行設置,則可以在實例上定義write ,以便可以使用this.write()進行調用。 每個實例都有自己的函數副本,這通常是不必要的:

 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(); 

另外,您也可以將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(); 

如果你使用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(); 

對此 范圍疑問 下面的代碼可以工作

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();

這里的問題是,到您寫這篇文章的時候,這和foo構造函數的代碼已經不一樣了。 當您學習香草javascript時,您可能會發現人們也在做

var self = this
var that = this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM