2017年6月28日 星期三

[JS]網頁學習 第三章 Object Methods, Object Prototypes小節 心得小記

總覺得這是一個很好的參考範例,使用到 this 及帶有參數的 function,
因此特別收錄,以便隨時參閱:

<script>
function person(firstName,lastName,age,eyeColor) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    }
}
var myMother = new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.getElementById("demo").innerHTML =
"My mother's last name is " + myMother.lastName;
</script>
----

講述 prototype 若要新增新的 property/ method 不可使用如下
(新增一般已存在物件的syntax):


Person.nationality = "English";

因 prototype 並非已存在物件,而是建構子;
若要新增,則要在定義 prototype 區塊寫入。

但是允許以下作法,使用 prototype property:

Person.prototype.nationality = "English";
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};

沒有留言:

張貼留言