从别人的博客里面盗了2张图,这2张图将对象/实例/prototype/__proto__/constructor之间的关系描绘的很清楚。
1.prototype 为 function的属性,实例化的对象(即new之后的对象)没有prototype,只有__proto__,且指向声明该实力对象函数的prototype
2.babel 继承源码分析:
class Base{
constructor(){
this.myname = 'jack';
}
}
Base.$inject = ['$http']
Base.prototype.age = ;
class HostController extends Base{ }
编译后:
'use strict'; function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); }
//继承父类的原型方法
subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
//关键步骤,通过__proto__指向父类构造函数,实现父类静态属性,方法的继承
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
//该方法就是判断 实例所属
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Base = function Base() {
_classCallCheck(this, Base); this.myname = 'jack';
}; Base.$inject = ['$http'];
Base.prototype.age = ; var HostController = function(_Base) {
_inherits(HostController, _Base); function HostController() {
_classCallCheck(this, HostController); return _possibleConstructorReturn(this, (HostController.__proto__ || Object.getPrototypeOf(HostController)).apply(this, arguments));
} return HostController;
}(Base);
3.es6 中class extends 继承,不仅继承了父类在构造函数中定义的属性方法,还可以继承父类原型链上的属性和方法,最后还有,父类定义的静态属性和方法也能继承,只不过子类调用父类的静态方法必须写为:Child.xxx(子类.父类属性或方法)。
class Base{
constructor(){
this.name = 'jack'
}
say(){
console.log('.............');
}
} Base.inject = ['Base'];
Base.prototype.age = ; class Child extends Base{ } var c = new Child();
c.name;
c.say();
Child.inject;
4.在babel继承中,使用到了Object.setPrototypeOf()方法,该方法有2个参数:
Object.setPrototypeOf(obj,prototype):obj代表要目标对象,将prototype参数指定的对象赋给obj的__proto__,等同于:obj.__proto__ =
prototype;