それを行うための一般的な方法がかなりあります。私はそれらの3つを提供します:
1.) Function オブジェクトをコンストラクタとして、また継承された新しいオブジェクトのプロトタイプ オブジェクトとして使用する。実装は次のようになります。
var person = {
toString : function() {
return this.firstName + ' ' + this.lastName;
}
}
function extend(constructor, obj) {
var newObj = Object.create(constructor);
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
newObj[prop] = obj[prop];
}
}
return newObj;
}
var man = extend(person,
{
sex: "male",
age: "22"
});
var name = extend(man,
{
firstName: "Simo",
lastName: "Endre"
});
name.man;
name.toString();
2.) この場合、C# や Java などの言語で従来の継承をシミュレートするためのコンストラクターとして Function オブジェクトを使用します。オブジェクトのプロトタイプ プロパティはコンストラクタの役割で使用され、新しく作成されたオブジェクトはオブジェクト プロトタイプ ルートからすべてのプロパティを継承します。この場合、オブジェクトのプロトタイプには 1 種類の拡張ロールしかなく、効果的な実装は関数メソッドで行われます。
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.toString = function() {
return this.firstName + ' ' + this.lastName;
}
function inherit(func) {
// passing function arguments into an array except the first one which is the function object itself
var args = Array.prototype.slice.call(arguments, 1);
// invoke the constructor passing the new Object and the rest of the arguments
var obj = Object.create(func.prototype);
func.apply(obj, args);
//return the new object
return obj;
}
var man = inherit(Person, "Simo", "Endre");
man.toString();
3.) よく知られた継承モデル:
function extend(o) {
function F() {}
// We'll set the newly created function prototype property to the object.
//This act as a constructor.
F.prototype = o;
// Using the `new` operator we'll get a new object whose prototype is o.
return new F();
};