js中每一個構造函數都有一個prototype的屬性,prototype指向一個原型對象,而這個對象的屬性和方法都會被構造函數的實例所繼承,因此,需要一些共享的屬性和方法可以寫在構造函數的原型中
1 用prototype屬性可以向構造函數添加可繼承的屬性和方法,
注意constructor屬性指向prototype對象所在的構造函數,方法放在prototype中,屬性放在構造函數里,
實例,原型對象,構造函數,三者之間的關系:
實例有__proto__屬性指向原型對象
原型對象有constructor指針指向構造函數
構造函數又有prototype屬性指向原型對象
<script>
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person,
sayName: function(){
console.log(this.name);
}
}
var p = new Person('xxx',22);
p.sayName();//'xxx'
console.log(p.age);//22
</script>
2 一個同名屬性在實例和prototype對象中存在時,構造函數的實例采用構造函數里的this屬性,查找優先級類似於:實例>原型對象
<script>
function Person(age){
this.age = age;//創建實例時賦給實例的屬性
}
Person.prototype = {
constructor: Person,
name: 'xxx',
age: 22,
sayName: function(){
console.log(this.name);
}
}
var p = new Person(233);
console.log(p.age);//233
p.age = 333;
console.log(p.age);//333
</script>
3 原型的繼承
<script>
function Person(){
this.age = 233;//創建實例時賦給實例的屬性
}
Person.prototype = {
constructor: Person,
name: 'xxx',
age: 22,
sayName: function(){
console.log(this.name);
}
}
var p = new Person();
console.log(p.age);//233
p.age = 333;
console.log(p.age);//333
function Student(){
}
Student.prototype = new Person();//繼承
var s = new Student();
console.log(s.name);//'xxx'
s.name = 'qqq';
console.log(s.name);//'qqq'
</script>
4 原型鏈的概念(修改於2019-11-13 09:41:30)
從對象的__proto__一級一級往上找
<script> class Person{ constructor(name,age){ this.name = name; this.age = age; } toPrint(){ return 'name:'+this.name+','+'age:'+this.age; } } class Son extends Person{ constructor(name,age,sex){ super(name,age); this.sex = sex; } toCount(){ return this.toPrint()+','+'sex:'+this.sex; } } var son = new Son('z',22,'male'); console.log(son); console.log(son.toPrint()); console.log(son.toCount()); </script>
該對象的結構圖

5、對象中固有的方法(2019-11-30 補充)
以數組對象為例,.forEach,.indexOf()等為數組對象本身的方法
而數組對象的原型為Object,原型object有

代碼示例:
<script> class Parent { constructor(name) { this.name = name; } say() { console.log('this is Parent'); } } class Child extends Parent { constructor(name, age) { super(name); //調用父類 this.age = age; } speak() { console.log('this is Child'); } } var c = new Child('aaa', 233); c.say(); c.speak(); console.log(c); </script>
圖示:

8、原型鏈
所謂的原型鏈,指的是一個對象的__proto__屬性,及其一級一級__proto__的指向,一般會指向最后的Object(Object.prototype__proto__ = null)
