gpt4 book ai didi

javascript - 这在 javascript 构造函数属性中如何工作

转载 作者:行者123 更新时间:2023-11-29 17:15:57 25 4
gpt4 key购买 nike

我有一个代码如下:

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() 显示未定义。

现在,如果我稍作更改并具有以下列出的代码,则函数会显示值。为什么会发生这种情况是因为 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();

最佳答案

this.get_neighbours = function(){
return calc_neighbours();
};

您调用 calc_neighbours 时未提供上下文。这使得上下文成为全局上下文 (window),其中 pointsundefined

这就是为什么你必须称它为

this.calc_neighbours();

关于javascript - 这在 javascript 构造函数属性中如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17917177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com