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

时间:2016-02-27 20:23:02

标签: javascript arguments prototype

一切都在标题中......我知道使用原型创建的函数无法访问私有对象数据/函数,但是如果能够访问传递给对象的参数呢?被创造了?

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

谢谢!

2 个答案:

答案 0 :(得分:3)

没有。

原型上的函数没有在变量所在的函数中定义,因此他们无法访问它们。

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

this.word = word;

答案 1 :(得分:-1)

也许是这样的:

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