我有一个代码如下:
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();
Run Code Online (Sandbox Code Playgroud)
放置上面的代码后,该函数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();
};
}
Run Code Online (Sandbox Code Playgroud)
我没有对功能使用进行任何更改.即
var c_points = new Array(8,2);
var cell = new Cell(c_points);
cell.get_neighbours();
Run Code Online (Sandbox Code Playgroud)
在
this.get_neighbours = function(){
return calc_neighbours();
};
Run Code Online (Sandbox Code Playgroud)
你打电话calc_neighbours没有提供上下文.这使得背景下全球性的(window),其中points为undefined.
这就是你必须把它称为的原因
this.calc_neighbours();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |