JavaScript创建对象之原型模式

我们创建的每个函数都有一个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属性。

猜你喜欢

转载自blog.csdn.net/qq_20567691/article/details/84973374