function foo(name){
this.name = name;
this.bar = function() {
this.name = "John"
console.log("bar's name is " + this.name);
}
}
var blah = new foo("Peter");
console.log(blah.name);//"Peter"
blah.bar();//"bar's name is John"
console.log(blah.name);//"John"
在上面的示例中,如何在功能栏中创建“this”,引用bar,而不是它的所有者foo?期望的结果是:
var blah = new foo("Peter");
console.log(blah.name);//"Peter"
blah.bar();//"bar's name is John"
console.log(blah.name);//"Peter"
答案 0 :(得分:0)
blah.bar();//"bar's name is John"
在这里,您只需调用功能栏,如果您希望bar成为自己的对象(并且具有名称等属性),则需要执行以下操作:
var bar = new blah.bar();
这将创建您期望的输出。
答案 1 :(得分:0)
您的示例看起来根本不想使用this
,而是本地变量,它不是任何属性:
function Foo(name) {
this.name = name;
this.bar = function bar() {
var name = "John";
console.log("the name is " + name);
}
}
var blah = new Foo("Peter");
console.log(blah.name); // "Peter"
blah.bar();// "the name is John"
console.log(blah.name); // still "Peter"
请注意function's .name
(blah.bar.name
)是"bar"
(至少在我的示例中,在您的代码中它是空的),就像Foo.name
是{{1}一样你甚至无法设置它。