我們創建的每個函數都有一個prototype(原型)屬性,這個屬性是一個指針,指向一個對象。這個對象包含由該函數(構造函數)創建的所有實例共享的屬性和方法。如果按照字面意思來理解,那麼prototype就是通過調用構造函數而創建的那個對象實例的原型對象。
function SuperType(name) {
this.superColors = ['red', 'yellow']
this.superName = name
}
SuperType.prototype = {
constructor: SuperType,
name: 'lizuncong',
stars: ['good', 'bad'],
drawColor: function(){
console.log(this.superColors)
}
}
const supertype1 = new SuperType('supertype1')
const supertype2 = new SuperType('supertype2')
supertype1.stars.push('best')
supertype1.stars = ['best']
supertype1.name = 'hahahahaha'
console.log(supertype1)
console.log(supertype2)
當我們創建SuperType函數時,就會自動創建該函數的原型對象。
當我們通過new SuperType('supertype1')構造函數創建supertype1和supertype2實例時,supertype1和supertype2各自包含一個__proto__屬性,該屬性指向構造函數SuperType的原型對象。由於supertype1和supertype2都指向該原型對象,因這兩個實例共享name,stars屬性以及drawColor方法。
從下圖可以得出一下結論:
1.當我們通過supertype1.stars.push('best')爲stars添加一個元素時,可以看出supertype2.stars也改變了。
2.當我們通過supertype1.stars = ['best']以及supertype1.name = 'hahahahahaha'給supertype1添加屬性時,實際上是給這個supertype1實例添加的屬性,而不會影響它的原型對象。從圖中可以看出supertype1實例中保存着name以及stars屬性,其原型對象中同樣保存着一份name以及stars屬性。