第一种方式:(YUI implement)
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
第二种方式:
function extend2(Child, Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
}
第二种方式没有第一种方式效率高。
原因:properties of the child prototype are being duplicated instead of simply being looked up via the prototype chain during execution.
在执行期间,child原型的属性被复制了而不是通过原型链来进行查找。
Bear in mind that this is only true for properties containing primitive types. All objects (including functions and arrays) are not duplicated, because these are passed by reference only.
要注意:child原型中属性并不是全部被复制,如果属性是基本类型则被复制,如果属性是object类型(包括function和array)则只是一个引用(内存地址);
from:object-oriented-javascript
分享到:
相关推荐
John Resig的"Simple JavaScript Inheritance"提供了一种简洁的方法来实现这种继承模式,它受到了base2和PrototypeJS库的启发。 在Resig的实现中,关键在于如何处理`_super`,这是一个用来引用父类方法的关键字。...
This brief book explains the advantages of the object model, inheritance, both classical and prototypical, and shows how these concepts can be implemented in JavaScript. It also shows how object ...
JavaScript,作为一种广泛应用于Web开发的脚本语言,其高级特性如闭包(closures)、原型(prototype)和继承(inheritance)是理解其精髓的关键。本文将深入探讨这些概念,帮助开发者更好地掌握JavaScript的核心。 ...
更不用谈继承、多态了,为了模拟出一些其它面向对象编程语言的这些特性,有好多大牛写了给出了实现方式,看了John Resig的《Simple JavaScript Inheritance》这篇文章,深深被折服了,原来短短几十行javascript也...
##Augment 简介The world's smallest and fastest classical JavaScript inheritance pattern, augment, is a seven line function which allows you to write CoffeeScript style classes with a flair of ...
* Learn the options available for code reuse and inheritance in JavaScript * Study sample JavaScript approaches to common design patterns such as Singleton, Factory, Decorator, and more * Examine ...
Zakas thoroughly explores JavaScript's object-oriented nature, revealing the language's unique implementation of inheritance and other key characteristics. You'll learn: –The difference between ...
Reuse code with common patterns for inheritance Make your programs cleaner, faster and compatible with other programs and libraries Use object-oriented JavaScript for improving script performance ...
5. **继承(Inheritance)**:JavaScript通过原型链实现继承。子类的原型会指向父类的实例,从而继承其属性和方法。ES6的`class`语法也支持`extends`关键字进行继承。 ```javascript class Employee extends ...
Prototypal Inheritance, Prototype Cloning and the Flyweight Pattern, The Module Pattern, Unit Testing, Coming soon:, Architecting for Scale, Collaboration, Build, Continuous Integration, Deployment, ...
在JavaScript中,面向对象编程是实现复杂功能和代码复用的关键。继承是面向对象的核心特性之一,它允许一个对象(子类)获取另一个对象(父类)的属性和方法。本篇文章将深入探讨JavaScript实现继承的七种常见方式,...
Build sophisticated web applications by mastering the art of Object-Oriented Javascript About This Book Learn popular Object-Oriented programming (OOP) principles and design patterns to build robust ...