Javascript类、构造函数和种子值

Javascript class, constructor and seed value

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


以下问题的帮助将帮助我着手澄清许多疑问。到目前为止,我读到我可以通过函数语句在JS中拥有类,并使用JSON表示法来保存对象值。因此,在下面的代码中

  1. 如何编写包含一些形状值的testData变量
  2. 如何从testData初始化Shape对象。我可以通过分配每个成员来创建对象

    var obj = {
                x: testData[i].x,
                  y: testData[i].y,
                ...      
            };
    

这是正确的方法吗,或者我们可以使用这里描述的构造函数吗

var testData = [ {}, {} ]

//Shape class
var Shape = function(x, y, w, h) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.calculateArea = function() {
            alert("Area..");
};

func test() {
var arr = [];
for (var i=0,l=testData.length; i<l; i++) {
       var s = testData[i];
           var obj = // how to construct Shape object here  through constructor          
        };
arr.push(obj);
}

您可以使用new关键字构造一个新对象(在本例中为Shape(。所以你会使用:

var obj = new Shape(testData[i].x, testData[i].y, testData[i].w, testData[i].h);

假设您需要将testData作为JSON从服务器等传输。

testData = [{ x: 1, y: 1, w: 1, h: 1}, ...]

然后,正如@digitalFish建议的那样,您可以通过从每个测试数据元素创建Shape对象

var obj = new Shape(s.x, s.y, s.w, s.h);
arr.push(obj);

new运算符允许您通过其构造函数实例化对象。

var circle = new Shape(x, y, width, height);

此外,它不被称为JSON表示法(这将是JavaScript对象表示法(,它被称为对象文字表示法

当需要.apply时,新运算符在某些边缘情况下可能会导致问题。我相信最好的方法如下。这也是一个小DRYer,因为你不会在整个过程中重复"这个"。

var createShape = function(x, y, w, h) {
    return {
        x: x,
        y: y,
        w: w,
        h: h,
        calculateArea: function() {
            alert("Area..");
        }
    };
};
var a = createShape(1,2,3,4);
var b = createShape(4,3,2,1);
console.log(a, b);