在多态中的超类中使用子类原型中定义的变量

时间:2016-05-22 02:54:50

标签: javascript node.js

我构建了一个在Node JS中使用多态的代码。itemprojectModuletestCasebusinessComponent,我<sub-class>.prototype.create.itemType是我的超类; s子类。在我的例子中,除文件读取操作外,每个操作都是相同的。因此,我使用create()创建了具有var test = new projectModule(); test.create(); 函数的唯一新变量。当我打电话

create functions is called

控制台记录文本item表示使用itemType原型成功但代码无法正常工作,因为undefineditemType。如何使用var item = function () {}; item.prototype.create = function () { console.log('create functions is called'); if(itemType==='module') console.log('read module json'); if(itemType==='tc') console.log('read tc json'); if(itemType==='bc') console.log('read bc json'); } var projectModule = function () {}; projectModule.prototype = Object.create(item.prototype); projectModule.prototype.create.itemType = 'module'; var testCase = function () {}; testCase.prototype = Object.create(item.prototype); testCase.prototype.create.itemType = 'tc'; var businessComponent = function () {}; businessComponent.prototype = Object.create(item.prototype); businessComponent.prototype.create.itemType = 'bc'; //call the function var test = new projectModule(); test.create(); 变量?

na.action = NULL

1 个答案:

答案 0 :(得分:1)

看起来您需要有关原型继承如何在javascript中工作的信息。

您要找的是关键字this

here

中提取的示例代码
function Plant () {
​this.country = "Mexico";
​this.isOrganic = true;
}
​
​// Add the showNameAndColor method to the Plant prototype property​
Plant.prototype.showNameAndColor =  function () {
console.log("I am a " + this.name + " and my color is " + this.color);
}
​
​// Add the amIOrganic method to the Plant prototype property​
Plant.prototype.amIOrganic = function () {
​if (this.isOrganic)
console.log("I am organic, Baby!");
}
​
​function Fruit (fruitName, fruitColor) {
​this.name = fruitName;
​this.color = fruitColor;
}
​
​// Set the Fruit's prototype to Plant's constructor, thus inheriting all of Plant.prototype methods and properties.​
Fruit.prototype = new Plant ();
​
​// Creates a new object, aBanana, with the Fruit constructor​
​var aBanana = new Fruit ("Banana", "Yellow");
​
​// Here, aBanana uses the name property from the aBanana object prototype, which is Fruit.prototype:​
console.log(aBanana.name); // Banana​
​
​// Uses the showNameAndColor method from the Fruit object prototype, which is Plant.prototype. The aBanana object inherits all the properties and methods from both the Plant and Fruit functions.​
console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.