繁体   English   中英

JS原型是否可以访问初始化期间传递给对象的参数?

[英]Does JS prototype have access to the argument(s) passed to an object during initialization?

一切都在标题中……我知道使用原型创建的函数无法访问私有对象的数据/函数,但是访问在创建对象时传递给对象的参数又如何呢?

var Voice = function (word)
{
   /* 
      I know I can obviously do something like : 'this.word = word;'
      But I was wondering whether there is a standard way of calling an   
      argument from within a prototype function without having to do  
      the above ?
   */
};

Voice.prototype.speak = function ()
{
    console.log({{word}});
};

x = new Voice('all I can say is this');
x.speak();

谢谢!

没有。

原型中的函数未在变量所涉及的函数中定义,因此它们无法访问它们。

您可以将变量存储为对象属性,然后从那里读取它。

this.word = word;

也许是这样的:

 var Voice = function (word) { this.init_word = word; }; Voice.prototype.speak = function (){ console.log(this.init_word); }; x = new Voice('all I can say is this'); x.speak(); 

暂无
暂无

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

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