2016-06-29 2 views
1

Я знаю, что 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); 
    } 
}; 
+4

Это геттер (Свойство сбруя): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/get – nils

ответ

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 
+0

О, я это! Этот способ записи может установить динамическое значение для ключа. Я прав? –

+0

@NicoleWu да, в пути. Это означает, что вы можете выполнять логику при получении свойства. Примите мой ответ, если я помог :) –

Смежные вопросы