我的代码如下:
function Cell(center) {
this.center_cell = center;
calc_neighbours = function() {
var points = this.center_cell;
console.log(points); // displays undefined
};
this.get_neighbours = function() {
return calc_neighbours();
};
}
var c_points = new Array(8,2);
var cell = new Cell(c_points);
cell.get_neighbours();
放置上面的代码后,函数cell.get_neighbours()
显示为undefined。
现在,如果我稍作修改并列出以下代码,则函数会显示值。为什么会发生这种情况是因为函数范围或javascript对象属性中的变量范围。
以下是显示值的代码:
function Cell(center) {
this.center_cell = center;
this.calc_neighbours = function() {
var points = this.center_cell;
console.log(points); // displays undefined
};
this.get_neighbours = function() {
return this.calc_neighbours();
};
}
我没有对功能使用进行任何更改。即。
var c_points = new Array(8,2);
var cell = new Cell(c_points);
cell.get_neighbours();
答案 0 :(得分:5)
在
this.get_neighbours = function(){
return calc_neighbours();
};
如果没有提供上下文,请致电calc_neighbours
。这使得上下文成为window
为points
的全局上下文(undefined
)。
这就是你必须把它称为
的原因this.calc_neighbours();
答案 1 :(得分:0)
“this”是必需的,以便设置适当的上下文。没有“this”,一切都绑定到全局上下文(窗口),在这种情况下是不对的。因此,没有它,它将无法运作。这与Java和其他一些OO语言的编码方式略有不同。
答案 2 :(得分:0)
要在此处或其他地方强制使用上下文,您还可以使用call
:
calc_neighbours.call( this )