はJavaScriptには、保護された変数/プロパティはありません。しかし、継承クラスを同じスコープで宣言するときには、 "private"変数を再利用することができます。これは、プライベート変数がプロトタイプの "隠されたユーティリティ"にすぎない場合に可能です。
MyNamespace.Person = function Person(params) {
// private variables and functions, individual for each Person instance
var anything, id;
function execute_something() {}
// public properties:
this.name = "";
this.getId = function getId(){
// called a "privileged function", because it has access to private variables
}
}
MyNamespace.American = function(params) {
MyNamespace.Person.call(this, params); // inherit name and getId()
}
(function() { // new scope for
// hidden utility functions and other private things
function foo() { }
function helpJSON() { }
function fromJSON() { }
var bar;
(function(personProto) { // new scope for prototype module (not explicitly needed)
// "private" /static/ variables (and functions, if you want them private)
var personCount = 0;
personProto.clone = function clone() {
return this.constructor(myself); // or something
};
personProto.toJSON = function toJSON() {
// use of helpJSON()
};
personProto.fromJSON = fromJSON; // direct use
})(MyNamespace.Person.prototype);
(function(amiProto) {
// just the same as above, if needed
amiProto.special = function() {
// use foo() and co
};
})(MyNamespace.American.prototype = Object.create(MyNamespace.Person.prototype));
})();
これはアメリカのプロトタイプは、人のプロトタイプから自動的にクローン()、toJSON()とfromJSON()関数を継承する意味相続のJavaScriptの方法が、あります。もちろん上書き可能です。そして、機能、すなわち、単にそれらをコピー、あなたがそれを必要とし、より多くのモジュールのような方法を使いたくない場合、あなたはユーティリティ機能を再利用することができ、もちろん
new MyNamespace.American() instanceof MyNamespace.Person; // true
です:
(function() {
// hidden utility functions and other private things
var bar;
var personCount;
function foo() { }
function helpJSON() { }
function fromJSON() { }
function clone() {
return this.constructor(myself); // or something
}
function toJSON() { }
(function(personProto) { // new scope, not really needed
// private variables are useless in here
personProto.clone = clone;
personProto.toJSON = toJSON;
personProto.fromJSON = fromJSON;
})(MyNamespace.Person.prototype);
(function(amiProto) { // new scope, not really needed
// copied from personProto
amiProto.clone = clone;
amiProto.toJSON = toJSON;
amiProto.fromJSON = fromJSON;
// and now the differences
amiProto.special = function() {
// use foo() and co
};
})(MyNamespace.American.prototype);
})();
継承とプロトタイプについてもっと知りたい場合は、ここで大きな読書があります:http://killdream.github.com/blog/2011/10/understanding-javascript-oop/index.html私はあなたが行くことができると思います継承が始まるポイント3。 –
残念ながら、そのリンクは404エラーを表示します。 –
@Programmer_D:http://robotlolita.me/2011/10/09/understanding-javascript-oop.htmlに移動しました。もちろん、[旧バージョンを見る]こともできます(http://web.archive.org/web/20130127102509/http://killdream.github.com/blog/2011/10/understanding-javascript-oop/index .html) – Bergi