首先说下new一个对象的过程
function Person(name, age) {
this.name = name
this.age = age
}
var p1 = new Person('zhen', '22')
创建一个新的对象,this指向这个对象p1,执行上面的代码即对this赋值。
构造函数
此外构造函数就像一个模版。可以new出多个实例,使用instanceof可以判断当前对象属于哪个构造函数。
instanceof的判断逻辑
p1 instanceof Person
p1.proto 看是否能对应Person.prototype,对应返回true
p1 instanceof Object
p1的__proto__ 看是否能对应Object.prototype ,不对应 ;
再往原型链上查找 p1的__proto__的__proto__ 是否对应Object.prototype 对应 结束原型链的查找并返回 true;
p1 instanceof World
查找p1的原型链 直到原型链的顶点Object.prototype 都不能对应World.prototype,结束查找并返回false
function Person(name, age) {
this.name = name
this.age = age
console.log('this', this)
}
function World() {
}
var p1 = new Person('zhen', 22)
console.log('p1', p1)
console.log('p1 instanceof Person =', p1 instanceof Person)
console.log('p1 instanceof Object =', p1 instanceof Object)
console.log('p1 instanceof World =', p1 instanceof World)
最后可以说说new Vue 发生了什么
Vue
实际上是一个类,类在 Javascript 中是用 Function 来实现的,来看一下源码,在src/core/instance/index.js
中
this instanceof Vue 这就是为啥vue要强制用new了,因为要保持this指向创建的实例
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
<div id="app">
{{ message }}
</div>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})