JavaScript 对象原型
所有 JavaScript 对象都从原型继承属性和方法。
在前一章里,我们学到了如何使用对象构造器:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 对象</h1>
<p id="demo">
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFriend = new Person("埃隆", "马斯克", 50, "蓝色");
var myBrother = new Person("马克", "扎克伯格", 40, "绿色");
document.getElementById("demo").innerHTML =
"我朋友是 " + myFriend.age + "岁。 我表哥是 " + myBrother.age + "岁。";
</script>
</body>
</html>
我们已经认识到,您无法为已有的对象构造器添加新属性:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 对象</h1>
<p>您不能将新属性添加到构造函数。</p>
<p id="demo">
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.nationality = "美国";
var myFriend = new Person("埃隆", "马斯克", 50, "蓝色");
var myBrother = new Person("马克", "扎克伯格", 40, "绿色");
document.getElementById("demo").innerHTML =
"我朋友的国籍是 " + myFriend.nationality;
</script>
</body>
</html>
如需向构造器添加一个新属性,则必须把它添加到构造器函数:
实例
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 对象</h1>
<p id="demo">
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.nationality = "美国";
}
var myFriend = new Person("埃隆", "马斯克", 50, "蓝色");
var myBrother = new Person("马克", "扎克伯格", 40, "绿色");
document.getElementById("demo").innerHTML =
"我朋友的国籍是 " + myFriend.nationality + ". 我哥的国籍是 " + myBrother.nationality;
</script>
</body>
</html>
原型继承
所有 JavaScript 对象都从原型继承属性和方法。
日期对象继承自 Date.prototype。数组对象继承自 Array.prototype。Person 对象继承自 Person.prototype。
Object.prototype 位于原型继承链的顶端:
日期对象、数组对象和 Person 对象都继承自 Object.prototype。
向对象添加属性和方法
有时,您希望向所有给定类型的已有对象添加新属性(或方法)。
有时,您希望向对象构造器添加新属性(或方法)。
使用 prototype 属性
JavaScript prototype 属性允许您为对象构造器添加新属性:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 对象</h1>
<p id="demo">
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.nationality = "English";
var myFriend = new Person("埃隆", "马斯克", 50, "蓝色");
document.getElementById("demo").innerHTML =
"我朋友的国籍是 " + myFriend.nationality;
</script>
</body>
</html>
JavaScript prototype 属性也允许您为对象构造器添加新方法:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 对象</h1>
<p id="demo">
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName
};
var myFriend = new Person("埃隆", "马斯克", 50, "蓝色");
document.getElementById("demo").innerHTML =
"我朋友是 " + myFriend.name();
</script>
</body>
</html>
请只修改您自己的原型。绝不要修改标准 JavaScript 对象的原型。