13

在 Douglas Crockford 的JavaScript: The Good Parts中,他建议我们使用函数继承。这是一个例子:

var mammal = function(spec, my) {
    var that = {};
    my = my || {};

    // Protected
    my.clearThroat = function() { 
        return "Ahem";
    };

    that.getName = function() {
        return spec.name;
    };

    that.says = function() {
        return my.clearThroat() + ' ' + spec.saying || '';
    };

    return that;
};

var cat = function(spec, my) {
    var that = {};
    my = my || {};

    spec.saying = spec.saying || 'meow';
    that = mammal(spec, my);

    that.purr = function() { 
        return my.clearThroat() + " purr"; 
    };

    that.getName = function() { 
        return that.says() + ' ' + spec.name + ' ' + that.says();
    };

    return that;
};

var kitty = cat({name: "Fluffy"});

我遇到的主要问题是每次我创建一个mammalcatJavaScript 解释器时都必须重新编译其中的所有函数。也就是说,您无法在实例之间共享代码。

我的问题是:如何让这段代码更有效率?例如,如果我正在制作数千个cat对象,那么修改此模式以利用prototype对象的最佳方法是什么?

4

4 回答 4

8

mammal好吧,如果您打算大量制作or ,您就不能那样做cat。而是以老式的方式(原型)并通过属性继承。您仍然可以按照上面的方式执行构造函数,但that您可以使用表示基类my的隐式变量和一些变量(在本例中为)。thisthis.mammal

cat.prototype.purr = function() { return this.mammal.clearThroat() + "purr"; }

我会使用其他名称而不是my基本访问并将其存储在this构造cat函数中。在这个例子中,我使用mammal了,但如果你想静态访问全局mammal对象,这可能不是最好的。另一种选择是命名变量base

于 2010-03-14T02:34:54.137 回答
1

让我向您介绍从不使用prototype. 这是一个糟糕的编码练习,但会教你真正的经典继承,它总是与原型继承相比:

做一个 custructor:

function Person(name, age){
  this.name = name;
  this.age = age;
  this.sayHello = function(){return "Hello! this is " + this.name;}
}

创建另一个继承自它的 cunstructor:

function Student(name, age, grade){
  Person.apply(this, [name, age]);
  this.grade = grade
}

很简单!Studentcall(applies) Personwithnameagearguments自己处理grade参数。

现在让我们创建一个Student.

var pete = new Student('Pete', 7, 1);

Outpete对象现在将包含nameagegrade属性sayHello。它拥有所有这些财产。它们没有Person通过原型上行链接。如果我们改成Person这样:

function Person(name, age){
  this.name = name;
  this.age = age;
  this.sayHello = function(){
    return "Hello! this is " + this.name + ". I am " this.age + " years old";
  }
}

pete将不会收到更新。如果我们调用pete.sayHello,ti 将返回Hello! this is pete。它不会得到新的更新。

于 2013-03-07T06:44:40.823 回答
0

要正确使用基于 Javascript 原型的继承,您可以使用fastClass https://github.com/dotnetwise/Javascript-FastClass

你有更简单的inheritWith味道:

  var Mammal = function (spec) {
    this.spec = spec;
}.define({
    clearThroat: function () { return "Ahem" },
    getName: function () {
        return this.spec.name;
    },
    says: function () {
        return this.clearThroat() + ' ' + spec.saying || '';
    }
});

var Cat = Mammal.inheritWith(function (base, baseCtor) {
    return {
        constructor: function(spec) { 
            spec = spec || {};
            baseCtor.call(this, spec); 
        },
        purr: function() {
            return this.clearThroat() + " purr";
        },
        getName: function() {
            return this.says() + ' ' + this.spec.name + this.says();
        }
    }
});

var kitty = new Cat({ name: "Fluffy" });
kitty.purr(); // Ahem purr
kitty.getName(); // Ahem Fluffy Ahem

如果你非常关心性能,那么你有这样的fastClass味道:

var Mammal = function (spec) {
    this.spec = spec;
}.define({
    clearThroat: function () { return "Ahem" },
    getName: function () {
        return this.spec.name;
    },
    says: function () {
        return this.clearThroat() + ' ' + spec.saying || '';
    }
});

var Cat = Mammal.fastClass(function (base, baseCtor) {
    return function() {
        this.constructor = function(spec) { 
            spec = spec || {};
            baseCtor.call(this, spec); 
        };
        this.purr = function() {
            return this.clearThroat() + " purr";
        },
        this.getName = function() {
            return this.says() + ' ' + this.spec.name + this.says();
        }
    }
});

var kitty = new Cat({ name: "Fluffy" });
kitty.purr(); // Ahem purr
kitty.getName(); // Ahem Fluffy Ahem

顺便说一句,您的初始代码没有任何意义,但我从字面上尊重它。

fastClass效用:

Function.prototype.fastClass = function (creator) {
    var baseClass = this, ctor = (creator || function () { this.constructor = function () { baseClass.apply(this, arguments); } })(this.prototype, this)

    var derrivedProrotype = new ctor();

    if (!derrivedProrotype.hasOwnProperty("constructor"))
        derrivedProrotype.constructor = function () { baseClass.apply(this, arguments); }

    derrivedProrotype.constructor.prototype = derrivedProrotype;
    return derrivedProrotype.constructor;
};

inheritWith效用:

Function.prototype.inheritWith = function (creator, makeConstructorNotEnumerable) {
    var baseCtor = this;
    var creatorResult = creator.call(this, this.prototype, this) || {};
    var Derrived = creatorResult.constructor ||
    function defaultCtor() {
        baseCtor.apply(this, arguments);
    }; 
    var derrivedPrototype;
    function __() { };
    __.prototype = this.prototype;
    Derrived.prototype = derrivedPrototype = new __;

    for (var p in creatorResult)
        derrivedPrototype[p] = creatorResult[p];

    if (makeConstructorNotEnumerable && canDefineNonEnumerableProperty) //this is not default as it carries over some performance overhead
        Object.defineProperty(derrivedPrototype, 'constructor', {
            enumerable: false,
            value: Derrived
        });

    return Derrived;
};

define效用:

Function.prototype.define = function (prototype) {
    var extendeePrototype = this.prototype;
    if (prototype)
        for (var p in prototype)
            extendeePrototype[p] = prototype[p];
    return this;
}

[* 免责声明,我是开源包的作者,方法本身的名称将来可能会重命名` *]

于 2013-03-28T09:58:10.330 回答
0

如果您想要隐私并且您不喜欢原型制作,您可能会或可能不会喜欢这种方法:

(注:它使用 jQuery.extend)

var namespace = namespace || {};

// virtual base class
namespace.base = function (sub, undefined) {

    var base = { instance: this };

    base.hierarchy = [];

    base.fn = {

        // check to see if base is of a certain class (must be delegated)
        is: function (constr) {

            return (this.hierarchy[this.hierarchy.length - 1] === constr);
        },

        // check to see if base extends a certain class (must be delegated)
        inherits: function (constr) {

            for (var i = 0; i < this.hierarchy.length; i++) {

                if (this.hierarchy[i] == constr) return true;
            }
            return false;
        },

        // extend a base (must be delegated)
        extend: function (sub) {

            this.hierarchy.push(sub.instance.constructor);

            return $.extend(true, this, sub);
        },

        // delegate a function to a certain context
        delegate: function (context, fn) {

            return function () { return fn.apply(context, arguments); }
        },

        // delegate a collection of functions to a certain context
        delegates: function (context, obj) {

            var delegates = {};

            for (var fn in obj) {

                delegates[fn] = base.fn.delegate(context, obj[fn]);
            }

            return delegates;
        }
    };

    base.public = {
        is: base.fn.is,
        inherits: base.fn.inherits
    };

    // extend a sub-base
    base.extend = base.fn.delegate(base, base.fn.extend);

    return base.extend(sub);
};

namespace.MyClass = function (params) {

    var base = { instance: this };

    base.vars = {
        myVar: "sometext"
    }

    base.fn = {
        init: function () {

            base.vars.myVar = params.myVar;
        },

        alertMyVar: function() {

            alert(base.vars.myVar);
        }

    };

    base.public = {
        alertMyVar: base.fn.alertMyVar
    };

    base = namespace.base(base);

    base.fn.init();

    return base.fn.delegates(base,base.public);
};

newMyClass = new namespace.MyClass({myVar: 'some text to alert'});
newMyClass.alertMyVar();

唯一的缺点是由于隐私范围,您只能扩展虚拟类而不是可实例类。

这是我如何扩展 namespace.base 以绑定/取消绑定/触发自定义事件的示例。

// virtual base class for controls
namespace.controls.base = function (sub) {

    var base = { instance: this };

    base.keys = {
        unknown: 0,
        backspace: 8,
        tab: 9,
        enter: 13,
        esc: 27,
        arrowUp: 38,
        arrowDown: 40,
        f5: 116
    }

    base.fn = {

        // bind/unbind custom events. (has to be called via delegate)
        listeners: {

            // bind custom event
            bind: function (type, fn) {

                if (fn != undefined) {

                    if (this.listeners[type] == undefined) {
                        throw (this.type + ': event type \'' + type + '\' is not supported');
                    }

                    this.listeners[type].push(fn);
                }

                return this;
            },

            // unbind custom event
            unbind: function (type) {

                if (this.listeners[type] == undefined) {
                    throw (this.type + ': event type \'' + type + '\' is not supported');
                }

                this.listeners[type] = [];

                return this;
            },

            // fire a custom event
            fire: function (type, e) {

                if (this.listeners[type] == undefined) {
                    throw (this.type + ': event type \'' + type + '\' does not exist');
                }

                for (var i = 0; i < this.listeners[type].length; i++) {

                    this.listeners[type][i](e);
                }

                if(e != undefined) e.stopPropagation();
            }
        }
    };

    base.public = {
        bind: base.fn.listeners.bind,
        unbind: base.fn.listeners.unbind
    };

    base = new namespace.base(base);

    base.fire = base.fn.delegate(base, base.fn.listeners.fire);

    return base.extend(sub);
};
于 2011-05-11T13:38:52.500 回答