是什么"得到"在原型对象中意味着什么?

时间:2016-06-29 14:02:58

标签: javascript prototype

我知道ElementMetrics是构造函数,而原型对象具有键和值。但原型对象中的get是什么意思???

function ElementMetrics(element) {
  this.element = element;
  this.width = this.boundingRect.width;
  this.height = this.boundingRect.height;
  this.size = Math.max(this.width, this.height);
}

ElementMetrics.prototype = {
  get boundingRect () {
    return this.element.getBoundingClientRect();
  },

  furthestCornerDistanceFrom: function(x, y) {
    var topLeft = Utility.distance(x, y, 0, 0);
    var topRight = Utility.distance(x, y, this.width, 0);
    var bottomLeft = Utility.distance(x, y, 0, this.height);
    var bottomRight = Utility.distance(x, y, this.width, this.height);

    return Math.max(topLeft, topRight, bottomLeft, bottomRight);
  }
};

1 个答案:

答案 0 :(得分:1)

这意味着它可以像对象上的属性一样被调用,但它实际上是一个函数。

function Person () {
    this.firstName = "John";
    this.lastName = "Smith";
}

Person.prototype = {
    setFirstName: function (name) {
        this.firstName = name;
    },
    setLastName: function (name) {
        this.lastName = name;
    },
    get fullName () {
        // we can perform logic here
        return this.firstName + " " + this.lastName;
    }
};

var person = new Person();
person.setFirstName("Nicole");
person.setLastName("Wu");

console.log("The persons name is " + person.fullName); // The persons name is Nicole Wu