javascript - 原型(prototype)对象中的 "get"是什么意思?

标签 javascript prototype

我知道ElementMetrics是构造函数,原型(prototype)对象有键和值。但是原型(prototype)对象中的 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);
  }
};

最佳答案

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

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

关于javascript - 原型(prototype)对象中的 "get"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38101976/

相关文章:

javascript - 不要为触摸触发 onclick - Javascript

javascript - Photoshop Javascript 奇怪的行为

javascript - Object.prototype.isPrototypeOf 与 obj.prototype.isPrototypeOf

javascript - Vue 不更新全局 $prototype 变量

javascript - 为什么现在命令行的每个参数后面都有两个连字符 (--)?它起源于何处,为什么不使用单个连字符?

javascript - 如何使用 Vue.js mixins 替换字符串值?

javascript - 选择元素时无法找到 data-id

Javascript Worker 丢失属性

javascript - 原型(prototype)。 Ajax 请求参数作为嵌套的 json

javascript - 使用 object.create 和 new 运算符创建继承之间的区别