1.有的时候我们想要在所有已经存在的对象添加新的属性或方法。
另外,有时候我们想要在对象的构造函数中添加属性或方法。
使用 prototype 属性就可以给对象的构造函数添加新的属性:
<script> function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } Person.prototype.nationality = "English"; var myFather = new Person("John", "Doe", 50, "blue"); document.getElementById("demo").innerHTML = "我父亲对国籍是 " + myFather.nationality; </script>
<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 myFather = new Person("John", "Doe", 50, "blue"); document.getElementById("demo").innerHTML = "我对父亲是 " + myFather.name(); </script>