首先说下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)