KpT*_*tor 1 javascript variables scope this
我收到错误:
Uncaught TypeError: Cannot read property '1' of undefined
Run Code Online (Sandbox Code Playgroud)
运行以下内容时:
function Polygon(width, height) {
this.width = width;
this.height = height;
this.a = [1, 2, 3, 4, 5];
this.build = function() {
this.a.map(function(i, v) {
console.log(this.a[v])
});
}
}
var square = new Polygon(300, 300);
square.build();
Run Code Online (Sandbox Code Playgroud)
只有在尝试引用this.aArray函数(如Array.prototype.map和)中的变量时才会发生这种情况reduce.但是,代码在将变量存储在局部变量中时起作用,如下所示:
function Polygon(width, height) {
this.width = width;
this.height = height;
this.a = [1, 2, 3, 4, 5];
this.build = function() {
var b = this.a;
b.map(function(i, v){
console.log(b[v])
});
}
}
var square = new Polygon(300,300);
square.build();
Run Code Online (Sandbox Code Playgroud)
我的问题是:
每MDN文件为Array.prototype.map:
如果
thisArg提供了一个参数来映射,它将在调用时传递给回调,以用作其值.否则,将传递未定义的值以用作其此值.(重点补充)
这意味着,this在map函数未定义,因此您试图上使用括号标记undefined.这产生了TypeError,表示你正试图访问的属性undefined.
您也使用不当i.i是实际的元素或项目,而不是索引.你可以只记录i,不要下标a:
function Polygon(width, height){
this.width = width;
this.height = height;
this.a = [1, 2, 3, 4, 5];
this.build = function(){
this.a.map(function(i, v){
console.log(i);
}, this);
}
}
var square = new Polygon(300, 300);
square.build();Run Code Online (Sandbox Code Playgroud)
这将通过可选的thisArg作为Polygon的情况下,正确地记录.该参数明确说明了this上下文,允许访问this.a.
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |