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"});

mammal私がこれに関して抱えている主な問題は、またはJavaScriptインタープリターを作成するたびに、そのcat中のすべての関数を再コンパイルする必要があるということです。つまり、インスタンス間でコードを共有することはできません。

私の質問は、このコードをより効率的にするにはどうすればよいですか?たとえばcat、何千ものオブジェクトを作成している場合、オブジェクトを利用するためにこのパターンを変更する最良の方法は何prototypeですか?

4

4 に答える 4

8

mammalええと、あなたがたくさんのまたはを作ることを計画しているなら、あなたはそのようにそれをすることはできませんcat。代わりに、昔ながらの方法(プロトタイプ)を実行し、プロパティによって継承します。上記の方法でコンストラクターを実行することもできますが、代わりにthat、基本クラス(この例では)を表すmy暗黙的変数といくつかの変数を使用します。thisthis.mammal

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

基本アクセス以外の名前を使用して、コンストラクターmyに格納します。この例では使用しましたが、グローバルオブジェクトへの静的アクセスが必要な場合は、これが最適ではない可能性があります。別のオプションは、変数に名前を付けることです。thiscatmammalmammalbase

于 2010-03-14T02:34:54.137 に答える
1

を使用しないClassicalInheritanceを紹介します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
}

とてもシンプル!Studentで呼び出し(適用)Personし、引数はそれ自体nameage引数を処理gradeします。

次に、のインスタンスを作成しましょうStudent

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

Outpeteオブジェクトには、、、、およびプロパティが含まれるようnameになりますage。それはそれらすべてのプロパティを所有しています。それらは、プロトタイプを介してアップリンクされません。これに変更すると:gradesayHelloPersonPerson

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

プライバシーが必要で、プロタイピングが気に入らない場合は、このアプローチが好きかどうかはわかりません。

(注: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 に答える
0

Javascriptプロトタイプベースの継承を適切に使用するには、 https://github.com/dotnetwise/Javascript-FastClassを使用できます。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 に答える