在Java Script中使用原型有什么好处?

时间:2017-06-19 02:08:00

标签: javascript

以下是我的代码:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
} 

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

稍后,我们可以按如下方式向person对象添加属性:

myFather.nationality = "English";

使用Prototype可以完成同样的操作:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
} 


Person.prototype.nationality = "English";

实际问题:为什么我们应该在myFather.nationality = "English";进行对象时使用原型属性或函数?

请指导我。

0 个答案:

没有答案