这在javascript构造函数属性中是如何工作的
我有一个代码如下:这在javascript构造函数属性中是如何工作的,javascript,Javascript,我有一个代码如下: 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
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_neights()
显示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();
};
}
我没有对函数usage做任何更改。i、 e
var c_points = new Array(8,2);
var cell = new Cell(c_points);
cell.get_neighbours();
在
调用calc\u neights
,但不提供上下文。这使得上下文成为全局上下文(窗口
),其中点
为未定义
这就是为什么你必须称之为
this.calc_neighbours();
“this”是必需的,以便设置正确的上下文。如果没有“this”,所有内容都绑定到全局上下文(窗口),这在本例中是不正确的。因此,如果没有这一点,它将无法发挥作用。这与Java和其他一些OO语言的编码方式略有不同。要在此处或其他地方强制上下文,您也可以使用
调用
:
calc_neighbours.call( this )
calc_neighbours.call( this )