理解prototype
2024-10-16 21:38:12
从别人的博客里面盗了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;
http://www.cnblogs.com/xiaohuochai/p/5721552.html
最新文章
- 数百个 HTML5 例子学习 HT 图形组件 – 拓扑图篇
- HDU 5776 sum (模拟)
- Could not load oracle/sql/converter_xcharset/lx20354.glb.
- 初学者自学笔记-this的用法
- OC基础了解篇
- 解决laravel Class 'Doctrine\DBAL\Driver\PDOMySql\Driver' not found 错误
- 邮局 100分代码(dfs+多重剪枝)
- async/await 的使用
- Linux 系统下实践 VLAN
- vue 选城市三级联动
- Caused by: java.sql.SQLException: ORA-24816: 在实际的 LONG 或 LOB 列之后提供了扩展的非 LONG 绑定数据
- Node.js实战(七)之交互式解释器
- shiro实战系列(六)之Authorization(授权)
- 前端基础之HTML快速入门
- float属性详解
- 如何修改sharepoint中alert发送邮件模板
- 商铺项目(Logback配置与使用)
- c# AOP 文章地址
- Linux中top和free命令(6/15)
- C/C++中,空数组、空类、类中空数组的解析及其作用