一切都在标题中......我知道使用原型创建的函数无法访问私有对象数据/函数,但是如果能够访问传递给对象的参数呢?被创造了?
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();
谢谢!
答案 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();