-
Notifications
You must be signed in to change notification settings - Fork 138
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
一名【合格】前端工程师的自检清单之原型和原型链 #288
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1、理解原型设计模式以及
javascript
中的原型规则原型模式:使用构造函数的
prototype
属性来指定那些应该共用的属性和方法。javascript
语言中,除来undefined
,symbol
,其他类型都会被包装成对象来处理(Number、String、Boolean)
,来方便我们共享一些属性和方法。new
一个构造函数;{}
创建;Object
的一些方法;原型规则 :
in
操作符单独使用可以判断属性是否可以被对象访问,无论该属性存在实例中还是原型中;在使用for-in
循环时,返回的是所有能够通过对象访问的、可枚举的(enumerated)
属性,其中既包括存在于实例中的属性,也包括存在于原型中的属性。prototype
指向共享的对象,我们通过new
这个构造函数来获取这些共享的属性和方法;而每个对象都有一个__proto__
属性指向一个Object
。而new形成的实例,就是把__proto__
指向来构造函数的prototype
。prototype===
实例的__proto__
;String、Number、Boolean、Symbol、Undefined、Null
。Object
。2、instanceof的底层实现原理,手动实现一个instanceof
instanceof
是用来判断引用类型,也可以通过原型链实现继承关系的判断。instanceof
的实现实际上是调用JS
内部函数 [[HasInstance]] 来实现的。3、实现继承的几种方式以及他们的优缺点
继承是面向对象的编程中最重要的概念,在语言中都支持两种继承方式:接口继承和实现继承。接口继承只继承方法名,而实现继承则- 继承实际的方法。在Js中无法实现接口继承,只支持实现继承,也就是原型链继承。
原型链继承:利用原型让一个引用类型继承另一个引用类型的方法和属性。
缺点:构造函数原型上的属性在所有该构造函数构造的实例上是共享的,即属性没有私有化,原型上属性的改变会作用到所有的实例上。
借用构造函数继承:在构造子类构造函数时内部使用call或apply来调用父类的构造函数。
优缺点:实现了属性的私有化,但是子类无法访问父类原型上的属性。
组合继承:利用构造函数和原型链的方法,可以比较完美的实现继承。
寄生继承:即将
sub.prototype=new super改为sub.prototype=Object.creat(supper.prototype)
,避免了组合继承中构造函数调用了两次的弊端。4、至少说出一种开源项目(如
Node
)中应用原型继承的案例node
中继承通过util
中的inherites
方法来实现。接受两个参数,第一个参数是要继承的构造函数,第二个参数是父类的构造函数,通过子类的prototype
指向一个新对象,新对象是拷贝父类的prototype
,并修改constructor
指向子类自己。5、可以描述
new
一个对象的详细过程,手动实现一个new操作符new
一个对象的详细过程:__proto__
指向构造函数的prototype
;this
;6、理解
es6 class
构造以及继承的底层实现原理class的构造:
javascript
的底层离不开构造函数,可以说构造函数是js
语言的核心。而class
类是对构造函数的一种规范使用。创建一个类:
babel
转换:类的继承:类的继承是通过
extends
和super
来实现的。babel
转换:在理解
_inherits
函数之前我们需要明白:Function.__proto__===Function.prototype
;Function.prototype.__proto__.constructor===Object
;Function.__proto__.constructor===Function
;`_inherits``函数的核心就是
subClass.__proto__=superClass
;subClass.prototype__proto__=superClass.prototype
;superClass.prototype.constructor=subClass
;The text was updated successfully, but these errors were encountered: