1

私はjavascriptでOOテクニックを学ぼうとしていました。ほとんどのWebサイトは、プロトタイプの継承を使用しています。

しかし、私は次のことがなぜ悪いのかを理解しようとしています(そしてそれでもプロトタイプの継承ができることを達成することができます):

        //create parent class
    var Person = function (vId, vName) {
        this.Id = vId;
        this.Name = vName;

        this.Display = function () {
            alert("Id=" + this.Id);
        }
    };

    //create new class
    var Emp = function (vId, vName, vOfficeMail) {
        Person.call(this, vId, vName)
        this.OfficeEmail = vOfficeMail;

        this.Display = function () {
            alert("Id=" + this.Id + ", OfficeMail=" + this.OfficeEmail);
        }
    };

    //create instance of child class
    var oEmp = new Emp(1001, "Scott", "a@a.com"); //using Child's constructor
    //call display method in child class
    oEmp.Display();

    //create instance of parent class
    var oPerson = new Person(1002, "Smith"); //using Parent's constructor
    //call display method in parent class
    oPerson.Display();
4

2 に答える 2

4

これが私が最も重要だと思うことであり、簡単な説明です。

このコードは、オブジェクトごとに1回関数を作成します。

this.Display = function () {
    alert("Id=" + this.Id);
}

プロトタイプを使用すると、関数は代わりに1回だけ作成され、その種類のすべてのオブジェクトに適用されます。無駄なメモリとCPUパワーが少なくなります。

このコードは、私が話していることを示します。

var Person = function (vId, vName) {
        this.Id = vId;
        this.Name = vName;

        this.Display = function () {
            alert("Id=" + this.Id);
        }
    };

    var a = new Person(1, 2);
    var b = new Person(3, 4);

    var instanceEqual = (a.Display == b.Display);// false
    alert("Instance functions equal: " + instanceEqual);

    Person.prototype.Display2 = function () {
            alert("Id=" + this.Id);
        }

    var prototypeEqual = (a.Display2 == b.Display2);// true
    alert("Prototype functions equal: " + prototypeEqual);

Jsfiddle: http: //jsfiddle.net/nPnrk/

于 2012-07-08T20:16:06.723 に答える
2

プロトタイプオブジェクトを使用すると、多くのオブジェクトインスタンスで共有される動作をすべて1か所に保持できます。そこから、必要に応じて動的に変更または拡張でき、プロトタイプから継承するすべての構築済みオブジェクトの機能を即座に変更できます。

他にもいいことがありますが、私にとってはそれが最も重要なことです。

于 2012-07-08T20:13:52.083 に答える