JavaScript prototype(原型对象)
# 定义
prototype就是一个原型对象,所有的对象都是继承它
function Person(first, last, age, eyecolor) { //Person是一个对象,
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.nationality = "English";//这样的语法是不可以添加属性的
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
function Person(first, last, age, eyecolor) { //这样才可以添加新的属性,不过是不是太麻烦了,但我们可以在prototype中添加
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# prototype 继承
所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法:
Date对象从Date.prototype继承。Array对象从Array.prototype继承。Person对象从Person.prototype继承。
所有 JavaScript 中的对象都是位于原型链顶端的 Object 的实例。
# 添加属性和方法
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English"; //就是这么简单
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2021/08/13, 23:21:49