2

Paperコンストラクターにコンストラクターを継承させたいView。一時的なコンストラクターが必要であると読みましたがnew F()、コード内の子クラスのプロトタイプとともに親が変更されます。

function View() {};
function Paper() {};

View.prototype = {
    location: {
        "city": "UK"
    }
}


function F() {};

F.prototype = View.prototype;
Paper.prototype = new F();
Paper.prototype.constructor = Paper;

Paperのプロトタイプを変更しようとすると、次のようになります。

Paper.prototype.location.city = "US";

Viewのプロトタイプも変更されていることがわかりました!:

var view = new View();
console.log(view.location); //US! not UK

では、私のコードの何が問題なのですか? 親に影響を与えずにプロトタイプをオーバーライドするにはどうすればよいですか?

4

1 に答える 1

0

お気づきのように、JS での継承は注意が必要です。おそらく、私よりも賢い誰かが技術的な詳細について教えてくれますが、考えられる解決策は、 Dead Edwardsの厚意により、非常に小さな Base.jsフレームワークを使用することです。

編集: Dean Edward のフレームワークに合うように元のコードを再構築しました。

構文をマスターすると、継承は適切に機能します。コードに基づく可能な解決策は次のとおりです。

var View = Base.extend({
    constructor: function(location) {
        if (location) {
            this.location = location;
        }
    },

    location: "UK",

    getLocation: function() {
        return this.location;
    }
});

そしてそれを拡張します:

var Paper = View.extend({
    location: "US"
});

そしてそれをテストします:

var view = new View();
alert("The current location of the view is: " + view.getLocation());
var paper = new Paper();
alert("The location of the paper is: " + paper.getLocation());
alert("The current location of the view is: " + view.getLocation());

または、次の方法でも同じ結果が得られます。

var Paper = View.extend();

そしてテスト:

var view = new View();
alert("The current location of the view is: " + view.getLocation());
var paper = new Paper("US");
alert("The location of the paper is: " + paper.getLocation());
alert("The current location of the view is: " + view.getLocation());

どちらも次の 3 つのアラートを生成します。

The current location of the view is: UK
The location of the paper is: US
The current location of the view is: UK

これが役立つことを願っています!

于 2013-07-25T14:50:13.313 に答える