所有JavaScript對象都從原型繼承屬性和方法。
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>
<h3>JavaScript 對象</h3>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age;
</script>
</body>
</html>
我們還了解到,您無法向現有對象構造函數添加新屬性:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript對象</title>
<body>
<h3>JavaScript對象</h3>
<p>您無法向構造函數添加新屬性。</p>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.nationality = "English";
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality;
</script>
</body>
</html>
要向構造函數添加新屬性,必須將其添加到構造函數:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript對象</title>
<body>
<h3> JavaScript對象</h3>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.nationality = "English";
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML =
"我父親的國籍是 " + myFather.nationality + ". 我母親的國籍是: " + myMother.nationality;
</script>
</body>
</html>
所有JavaScript對象都從原型繼承屬性和方法:
Object.prototype位于原型繼承鏈的頂部:Date對象,Array對象和Person對象繼承自Object.prototype。
有時,您希望向給定類型的所有現有對象添加新屬性(或方法)。有時您想要向對象構造函數添加新屬性(或方法)。
JavaScript prototype屬性允許您向對象構造函數添加新屬性:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
JavaScript prototype屬性還允許您向對象構造函數添加新方法:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
更好的原型對象的文章
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。