在JavaScript中,每一个对象会有一个原型对象。对象会从原型对象继承一些属性和方法。javascript
在JavaScript中,访问一个对象的属性时,JS引擎会首先在该对象自身上线查找该属性。若是找到了,则直接返回该属性的值;若是没有找到,则会去改对象的原型上面继续查找。若是对象的原型上面也没有这个属性,则继续在原型对象的上原型上面查找,如此一级级继续往上,直到原型为null,此时JS引擎返回该对象的属性值为undefined。java
/** * two methods to implement inheritance; */
function Base(type){
this.type = type;
}
Base.prototype.base=function(){
console.log(`${this.type} is in base func`);
}
// method one
function Sub(type){
this.type = type;
}
Sub.prototype = Object.create(new Base('base'));
Sub.prototype.sub=function(){
console.log(`${this.type} is in sub func`);
}
// method two
function Foo(type){
this.type = type;
}
Object.setPrototypeOf( Foo.prototype, new Sub('sub'));
Foo.prototype.foo=function(){
console.log(`${this.type} is in foo func`);
}
let sub = new Sub('sub1');
sub.base();
sub.sub();
sub instanceof Sub; // true
sub instanceof Base; // true
let foo = new Foo('foo1');
foo.base();
foo.sub();
foo.foo();
foo instanceof Foo; // true
foo instanceof Sub; // true
foo instanceof Base; // true
复制代码
预测下面几个表达式的结果函数
Object.getPrototypeOf(function(){}).constructor === Function;
Object.getPrototypeOf(Function).constructor === Function;
Object.getPrototypeOf(Object.getPrototypeOf(Function)).constructor === Object;
复制代码
答案:ui
true;
复制代码
let obj = Object.create(null);
console.log(obj);
复制代码
这篇medium上得到8.6K赞的文章Prototypes in JavaScript讲得很清楚了。this