Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

从js原型继承深入理解instanceof操作符 #12

Open
shiiiiiiji opened this issue May 7, 2018 · 0 comments
Open

从js原型继承深入理解instanceof操作符 #12

shiiiiiiji opened this issue May 7, 2018 · 0 comments

Comments

@shiiiiiiji
Copy link
Owner

shiiiiiiji commented May 7, 2018

在学习js原型继承时,有如下代码:

function SuperType(){
	this.property = true;
}

SuperType.prototype.getProperty = function(){
	return this.property;
}


function SubType(){
	this.subProperty = false;
}

SubType.prototype = new SuperType();

SubType.prototype.getSubProperty = function(){
	return this.subProperty;
}

var instance = new SubType();

然后,再执行instance instanceof SubType时,得到的结果的true。

最开始了解instanceof操作符时,会认为这个操作符的含义是是否是XX的实例的含义。

但在理解js的原型继承时,构造函数(引用类型)的原型对象被重写为另外一个引用类型(构造函数)的实例,这里新的原型对象并没有包含指向构造函数的constructor属性,所以我就会认为“新创建的实例并不是原引用类型(构造函数)的实例”,认为上面应该返回false。

这样的理解其实是片面的,虽然在代码原理层面,原型链和原构造函数已经没有了任何关系(因为重写的原型对象没有构造函数属性了)。但是,继承的含义却保证了“实例是原引用类型(构造函数)的实例”。

再从instanceof操作符的原理上看,深入可参见这篇文章JavaScript instanceof 运算符深入剖析,可以了解到其本质含义是:“沿着原型链来查找是否包含指定构造函数(引用类型)的原型对象”,而构造函数到原型对象的单向引用还是保持的。

综上,instance instanceof SubType返回true就不难理解了。

@shiiiiiiji shiiiiiiji added edit and removed edit labels May 7, 2018
@shiiiiiiji shiiiiiiji changed the title 深入instanceof操作符 从js原型继承深入理解instanceof操作符 May 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant