// the parent constructor

function Parent(name) {

    this.name = name || 'Adam';

}

// adding functionality to the prototype

Parent.prototype.say = function () {

    return this.name;

};

// empty child constructor

function Child(name) {}

inherit(Child, Parent);

A method say() added to the parent constructor’s prototype, and a call to a function called inherit() that takes care of the inheritance. The  inherit() function is not provided by the language, so you have to implement it yourself.

Classical Pattern #1—The Default Pattern

Create an object using the  Parent() constructor and assign this object to the Child()’s prototype.

function inherit(C, P) {

    C.prototype = new P();
} var kid = new Child(); kid.say(); // "Adam"
  1. Following the Prototype Chain

  1. Drawbacks when Using Pattern #1
  1. Inherit both own properties added to this and prototype properties.

Note: reusable members should be added to the prototype.

  1. It doesn't enable you to pass parameters to child constructor, which the child then passes to the parent.

Classical Pattern #2 -- Rent-a-Constructor

Passing arguments from the child to the parent.

function Child(a, c, b, d) {

    Parent.apply(this, arguments);

}

// a parent constructor

function Article() {

    this.tags = ['js', 'css'];

}

var article = new Article();

// a blog post inherits from an article object

// via the classical pattern #1

function BlogPost() {}

BlogPost.prototype = article;

var blog = new BlogPost();

// note that above you didn't need `new Article()`

// because you already had an instance available

// a static page inherits from article

// via the rented constructor pattern

function StaticPage() {

    Article.call(this);

}

var page = new StaticPage();

alert(article.hasOwnProperty('tags')); // true

alert(blog.hasOwnProperty('tags')); // false

alert(page.hasOwnProperty('tags')); // true
  1. The Prototype Chain

The inheritance was a one-off action that copied parent’s own properties as child’s own properties and that was about it; no __proto__ links were kept.

// the parent constructor

function Parent(name) {

    this.name = name || 'Adam';

}

// adding functionality to the prototype

Parent.prototype.say = function () {

    return this.name;

};

// child constructor

function Child(name) {

    Parent.apply(this, arguments);

}

function showMsg(msg) {

    $('#msg').append(msg).append('<br/>');

}

$(function () {

    var kid = new Child("Patrick");

    showMsg(kid.name); // "Patrick"

    showMsg(typeof kid.say); // "undefined"

});

  1. Multiple Inheritance by Borrowing constructors

Implement multiple inheritance simply by borrowing from more than one constructor

function Cat() {

    this.legs = 4;

    this.say = function () {

        return "meaowww";

    }

}

function Bird() {

    this.wings = 2;

    this.fly = true;

}

function CatWings() {

    Cat.apply(this);

    Bird.apply(this);

}
var jane = new CatWings(); console.dir(jane);

  1. Pros and Cons of the Borrowing Constructor Pattern

Pros: Get true copies of the parent's own members and there's no risk that a child can accidentally overwrite a parent's property.

Cons: Nothing from the prototype gets inherited.

Classical Pattern #3—Rent and Set Prototype

function Child(a, c, b, d) {

    Parent.apply(this, arguments);

}

Child.prototype = new Parent();

The benefit is that the result objects get copies of the parent’s own members and references to the parent’s reusable functionality (implemented as members of the prototype). The child can also pass any arguments to the parent constructor. This behavior is probably the closest to what you’d expect in Java; you inherit everything there is in the parent, and at the same time it’s safe to modify own properties without the risk of modifying the parent.

A drawback is that the parent constructor is called twice, so it could be inefficient. At the end, the own properties (such as name in our case) get inherited twice.

// the parent constructor
function Parent(name) {
this.name = name || 'Adam';
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};
// child constructor
function Child(name) {
Parent.apply(this, arguments);
}
Child.prototype = new Parent(); function showMsg(msg) {
$('#msg').append(msg).append('<br/>');
}
var kid = new Child("Patrick");
kid.name; // "Patrick"
kid.say(); // "Patrick"
delete kid.name; kid.say(); // "Adam"

Classical Pattern #4—Share the Prototype

This gives you short and fast prototype chain lookups because all objects actually share the  same  prototype.

function inherit(C, P) {

    C.prototype = P.prototype;

}

Drawback

if  one  child  or  grandchild somewhere down the inheritance chain modifies the prototype, it affects all parents and grandparents.

Classical Pattern #5—A Temporary Constructor

An empty function  F(), which serves as a proxy between the child and the parent. F()’s  prototype property points to the prototype of the parent. The prototype of the child is an instance of the blank function:

function inherit(C, P) {

    var F = function () {};

    F.prototype = P.prototype;

    C.prototype = new F();

}

In this pattern, any members that the parent constructor adds to this are not inherited.

  1. Storing the Superclass

The property is called uber because “super” is a reserved word and “superclass” may

lead the unsuspecting developer down the path of thinking that JavaScript has classes.

Here’s an improved implementation of this classical pattern:

function inherit(C, P) {

    var F = function () {};

    F.prototype = P.prototype;

    C.prototype = new F();

    C.uber = P.prototype;

}
  1. Resetting the Constructor Pointer

If you don’t reset the pointer to the constructor, then all children objects will report that Parent() was their constructor, which is not useful.

// parent, child, inheritance

function Parent() {}

function Child() {}

inherit(Child, Parent);

// testing the waters

var kid = new Child();

kid.constructor.name; // "Parent"

kid.constructor === Parent; // true

function inherit(C, P) {

    var F = function () {};

    F.prototype = P.prototype;

    C.prototype = new F();

    C.uber = P.prototype;

    C.prototype.constructor = C;

}

Create temporary (proxy) constructor once and only change its prototype. You can use an immediate function and store the proxy function in its closure:

var inherit = (function () {

        // This will only be executed once which means only one function object is created for every inheritance.

        var F = function () {};     

        return function (C, P) {

        F.prototype = P.prototype; // F.prototype.constructor is pointed to Parent.

        C.prototype = new F();

        C.uber = P.prototype;

        C.prototype.constructor = C;

       }

}());

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance的更多相关文章

  1. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  2. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  3. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  4. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  5. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  6. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

  7. JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns

    In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...

  8. JavaScript Patterns 5.9 method() Method

    Advantage Avoid re-created instance method to this inside of the constructor. method() implementatio ...

  9. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

随机推荐

  1. ComboBoxEdit设置选项值(单选 多选)

    网上搜索的 例子 加 自己的 一点点补充 lookupedit 设置选项值: private void LookUpEditFormTest_Load(object sender, EventArgs ...

  2. CSRF 攻击介绍

    CSRF是什么? CSRF(Cross-site request forgery),中文名称:跨站请求伪造,也被称为:one click attack/session riding,缩写为:CSRF/ ...

  3. How do I set the default schema for a user in MySQL

    http://stackoverflow.com/questions/12426320/how-do-i-set-the-default-schema-for-a-user-in-mysql   up ...

  4. HTML标签小结

    HTML:超文本标记语言 超:超链接       超文本:超出文本(可加入图片,文字,音频视频播放器)  标记:标签 HTML文档 以<html...>开始 , 以</html> ...

  5. 第 16 章 CSS 盒模型[上]

    学习要点: 1.元素尺寸 2.元素内边距 3.元素外边距 4.处理溢出 主讲教师:李炎恢 本章主要探讨 HTML5 中 CSS 盒模型,学习怎样了解元素的外观配置以及文档的整体布局. 一.元素尺寸 C ...

  6. 关于JAVA数据储存

    关于JAVA数据储存: 在JAVA中,有六个不同的地方可以存储数据: 1. 寄存器(register) 这是最快的存储区,因为它位于不同于其他存储区的地方--处理器内部.但是寄存器的数量极其有限,所以 ...

  7. servlet基本原理(手动创建动态资源+工具开发动态资源)

    一.手动开发动态资源 1 静态资源和动态资源的区别 静态资源: 当用户多次访问这个资源,资源的源代码永远不会改变的资源. 动态资源:当用户多次访问这个资源,资源的源代码可能会发送改变. <scr ...

  8. InfluxDB学习之InfluxDB连续查询(Continuous Queries)

    在上一篇:InfluxDB学习之InfluxDB数据保留策略(Retention Policies) 中,我们介绍了 InfluxDB的数据保留策略,数据超过保存策略里指定的时间之后,就会被删除. 但 ...

  9. quickstart.sh

    #!/bin/bashjava_pid=`ps -ef | grep java | grep 'com.kzhong.huamu.sisyphus.QuickStartServer' | awk '{ ...

  10. viewport ——视区概念,为 自适应网页设计

    什么是Viewport 手机浏览器是把页面放在一个虚拟的“窗口”(viewport)中,通常这个虚拟的“窗口”(viewport)比屏幕宽,这样就不用把每个网页挤到很小的窗口中(这样会破坏没有针对手机 ...