您好我正在尝试获取该声明中属性名称的refence但是当我在fun属性(函数定义)中打印this.name
时,我的对象它不起作用,而是当我使用{ {1}}在this.name
属性中,它可以正常工作。
为什么?
这是我的代码
this.img
打印未申报....
答案 0 :(得分:2)
尝试将scoped存储到变量
中var submenu = new function(){
var that = this;
that.name = museum[i].name,
that.title = 'It will merge row',
that.img ="img/"+that.name + '.png', //it work
that.fun = function (data) {
console.log(that.name); //it doesn't work
}
};
发生此错误是因为"此"是一个范围广泛的关键字,范围的一点变化将影响关键字内容。因此,您将关键字存储在要使用的范围内,而是使用该变量。
答案 1 :(得分:2)
因为this
个关键字has some funny behaviours,它会根据您调用函数的方式而改变!
var submenu = new function(){
var self = this;
//in here, `this` refers to the `submenu` function
self.name = museum[i].name;
self.title = 'It will merge row';
self.img = 'img/'+ self.name + '.png';
self.fun = function (data) {
console.log(self.name);
//but in here `this` refers to the `fun` function
}
};
答案 2 :(得分:0)
每个函数调用都有scope and a context与之关联。 Context始终是this
关键字的值,它是对“拥有”当前正在执行的代码的对象的引用。尝试将子菜单功能的上下文分配给变量,并在内部函数中使用该变量
var submenu = new function(){
var that = this;
that.name = museum[i].name,
that.title = 'It will merge row',
that.img ="img/"+that.name + '.png',
that.fun = function (data) {
console.log(that.name);
}
}
答案 3 :(得分:0)
this.name
函数中没有this.fun
var!请创建一个本地副本,如下所示
var submenu = new function(){
this.name = museum[i].name,
this.title = 'It will merge row',
this.img ='img/'+this.name + '.png', //it work
var clone=this;
this.fun = function (data) {
console.log(clone.name); //it doesn't work
}
};
答案 4 :(得分:0)
编写您的对象并使用原型设计:
var submenu = function(){
this.name = museum[i].name;
this.title = 'It will merge row';
this.img ='img/' + this.name + '.png';
};
submenu.prototype.fun = function (data) {
console.log(this.name);
};