匿名函数/构造函数中的关键字

this keyword inside anonymous function/constructor

本文关键字:关键字 构造函数 函数      更新时间:2023-09-26

在某种程度上,我知道代码中发生了什么,只是为了澄清我的疑问,我已经发布了这个问题

JavaScript

Point = function (x, y)     //Here anonymous constructor is define 
{
    this.x = x;
    this.y = y;
}
var points=[] 
points.push(new Point(centerX + radius * Math.sin(angle),centerY - radius * Math.cos(angle)));  //object is created and push in the array

和访问点数组的值,我可以写点[I].x?

是,检查这个

   var Point = function (x, y)     //Here anonymous constructor is define
{
    this.x = x;
    this.y = y;
}
var points = [];
points.push(new Point(2,5));
points.push(new Point(3,11));
points.push(new Point(9,1));
for(var i = 0; i <points.length; i++){
console.log(points[i].x);
console.log(points[i].y);
};

正确,您可以使用索引i访问对象,然后对对象解引用以访问其属性/成员

var Point = function (x, y)
{
    this.x = x;
    this.y = y;
}
var points = [];
points.push(new Point(1, 2));
var point = points[0];
alert(point.x == point[0].x);