单例模式

一个类只有一个实例,单例有全局状态。vue2采用单例模式,全局只有一个Vue构造函数,所有配置、插件都挂载在上面。这导致全局状态污染,多个应用难以隔离。

function Person () {
    this.name = 'Jack'
    this.age = 18
}
Person.prototype.sayHi = function () {
    console.log('hello world')
}
const p1 = new Person()
const p2 = new Person()

p1 instanceof Person   // true,说明Person 这个构造函数的原型在实例p1的原型链上,图可见:原型链结构
p1.sayHi === p2.sayHi  // true,说明指向的是原型链上的同一个方法,证明资源共享


let p6 = Person()      // undefined,构造函数必须使用 new 关键字

results matching ""

    No results matching ""