用 Object.create实现类式继承
来源:互联网 发布:大数据经济学 编辑:程序博客网 时间:2024/06/03 07:36
下面的例子演示了如何使用Object.create()
来实现类式继承。这是一个所有版本JavaScript都支持的单继承。
// Shape - superclassfunction Shape() { this.x = 0; this.y = 0;}// superclass methodShape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('Shape moved.');};// Rectangle - subclassfunction Rectangle() { Shape.call(this); // call super constructor.}// subclass extends superclassRectangle.prototype = Object.create(Shape.prototype);Rectangle.prototype.constructor = Rectangle;var rect = new Rectangle();console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // trueconsole.log('Is rect an instance of Shape?', rect instanceof Shape); // truerect.move(1, 1); // Outputs, 'Shape moved.'
如果你希望能继承到多个对象,则可以使用混入的方式。
function MyClass() { SuperClass.call(this); OtherSuperClass.call(this);}// inherit one classMyClass.prototype = Object.create(SuperClass.prototype);// mixin anotherObject.assign(MyClass.prototype, OtherSuperClass.prototype);// re-assign constructorMyClass.prototype.constructor = MyClass;MyClass.prototype.myMethod = function() { // do a thing};
Object.assign 会把 OtherSuperClass
原型上的函数拷贝到 MyClass
原型上,使 MyClass 的所有实例都可用 OtherSuperClass 的方法。Object.assign 是在 ES2015 引入的,且可用 polyfilled。要支持旧浏览器的话,可用使用 jQuery.extend() 或者 _.assign()。
阅读全文
0 0
- 用 Object.create实现类式继承
- 使用Object.create实现类式继承
- javascript基础之十一(基于Object.create()实现类的继承)
- 原型式继承-Object.create()
- Class.create和 Object.extend继承操作
- 谈谈 Object.create ,JS的原型继承
- 学习prototypejs中的继承实现机制(一): Object.extend()、Class.create()、Class#addMethods()的使用
- Object.create() 是什么?继承(继承特定的)
- Object.create方法及其在继承上的应用
- 实现ES5以下兼容,Object.create()、getElementsByClassName()
- 实现JavaScript的Object.create方法
- Object C 实现 “多继承”
- Object.create
- Object.create
- Python - 继承object类
- Python - 继承object类
- 继承之Object类
- C++实现 反射 机制( 即根据 类名 创建 类实例)Create C++ Object Dynamically
- c++中的auto和for循环
- 17.11.29,web学习第十五天,还有一年,努力吧青年Request
- 编码
- nginx反向代理实践
- TOMCAT环境变量配置
- 用 Object.create实现类式继承
- 获取jQuery对象 Uncaught ReferenceError: jQuery is not defined(…) 的解决办法
- 这是一个转型AI的励志故事,从非科班到拿下竞赛一等奖
- C和指针之动态内存分配之(编写calloc函数,函数内部使用malloc函数来获取内存)
- Hexo + GitHub搭建个人博客 --- Standard Edition
- python参数
- POJ3660---Cow Contest(Floyd,传递闭包,连通)
- Flink DataSet API 使用示范
- 判断一个链表是否是回文结构 Python 版