因此特別收錄,以便隨時參閱:
<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;
};
沒有留言:
張貼留言