使用JavaScript多态在子类中创建唯一变量而不覆盖
16lz
2021-01-22
I want to use item.create()
in projectModule
, testCase
and businessFunction. because it's same prototype as item
's I copied the item
's to other functions. But i want have a one unique variable for these three functions which is called itemType
. I tried this. But an exception is occurred. How can I place a unique variable for these three functions without overriding them?
我想在projectModule,testCase和businessFunction中使用item.create()。因为它与项目的原型相同,我将项目复制到其他功能。但是我希望这三个函数有一个唯一的变量叫做itemType。我试过这个。但是发生了一个例外。如何在不覆盖它们的情况下为这三个函数放置一个唯一变量?
Exception:
projectModule.create.prototype.itemType = 'module';
TypeError: Cannot read property 'prototype' of undefined
JavaScript Code
var item = function () {};
item.prototype.create = function (projectName, itemName) {
console.log(projectName);
console.log(itemName);
console.log(itemType);
};
/**
* create module
*/
var projectModule = function () {};
projectModule.prototype = Object.create(item.prototype);
projectModule.create.prototype.itemType = 'module';
/**
* create tc
*/
var testCase = function () {};
testCase.prototype = Object.create(item.prototype);
testCase.create.prototype.itemType = 'tc';
/**
* create bc
*/
var businessComponent = function () {};
businessComponent.prototype = Object.create(item.prototype);
businessComponent.create.prototype.itemType = 'bc';
1 个解决方案
#1
0
This seems to have solved the error for me. Swapped .create and .prototype around.
这似乎解决了我的错误。交换.create和.prototype。
var projectModule = function () {};
projectModule.prototype = Object.create(item.prototype);
projectModule.prototype.create.itemType = 'module';
/**
* create tc
*/
var testCase = function () {};
testCase.prototype = Object.create(item.prototype);
testCase.prototype.create.itemType = 'tc';
/**
* create bc
*/
var businessComponent = function () {};
businessComponent.prototype = Object.create(item.prototype);
businessComponent.prototype.create.itemType = 'bc';
更多相关文章
- 轮播图---可以动态添加图片,(封装成一个函数)
- 从单击使用属性作为变量进行AJAX调用。
- javascript高阶函数map和reduce
- jQuery插件:如何将元素引用传递给回调函数?
- Javascript等待函数的结束,包括node.js的异步MYSQL查询?
- JavaScript数组操作函数方法详解
- JavaScript:使用函数参数检索javascript对象键
- 由浅到深的分析Javascript OO之写类方式之一:构造函数
- 在JavaScript中访问PHP变量[重复]