Concesso Sono un noob javascript (nel migliore dei casi). Il seguente codice sembra funzionare correttamente. Qualche idea su come mantenere lo stesso approccio di "inizializzatore" e farlo funzionare senza usare __proto__
e senza convertire tutto in funzioni di costruzione?alternativa per il __proto__ deprecato
var Employee =
{
paygrade: 1,
name: "",
dept: "general",
init: function()
{
return this;
},
salary: function()
{
return this.paygrade * 30000;
}
};
var WorkerBee =
{
paygrade: 2,
projects: ["Project1", "Project2"],
init: function()
{
this.__proto__ = Inherit_Employee; // Inherit My Employee "Pseudo Prototype"
return this;
}
};
var SalesPerson =
{
dept: "Sales",
quota: 100,
init: function()
{
this.__proto__ = Inherit_WorkerBee; // Inherit My WorkerBee "Pseudo Prototype"
return this;
}
};
var Engineer =
{
dept: "Engineering",
machine: "im the start machine",
init: function()
{
this.__proto__ = Inherit_WorkerBee; // Inherit My WorkerBee "Pseudo Prototype"
return this;
}
};
var Inherit_Employee = Object.create(Employee).init(); // Create My Employee Pseudo-Prototype
var Inherit_WorkerBee = Object.create(WorkerBee).init(); // Create My WorkerBee Pseudo-Prototype
var jane = Object.create(Engineer).init();
var jill = Object.create(Engineer).init();
Ho un approccio che funziona, ma mi chiedo se esiste un approccio più efficiente. Per ora, quello che ho fatto è sostituire le linee che fanno riferimento allo __proto__
con una chiamata alla mia funzione di ereditarietà come questa.
init: function()
{
inherit(this, WorkerBee); // Inherit WorkerBee
return this;
}
E questa è la mia eredita funzione
function inherit(childObject, parentObject)
{
// childObject inherits all of parentObjects properties
//
for (var attrname in parentObject)
if (childObject[attrname] == undefined)
childObject[attrname] = parentObject[attrname];
// childObject runs parentObject 'init' function on itself
//
for (var attrname in parentObject)
if (typeof parentObject[attrname] == "function")
if (attrname == 'init')
parentObject[attrname].call(childObject);
}
Questo potrebbe aiutarti: http://www.webdeveasy.com/javascript-prototype/ – Naor