当您使用 require
并加载模块时,您似乎能够创建具有属性的函数或可以作为函数调用的对象。
console.log(require('events').EventEmitter);
//{ [Function: EventEmitter] defaultMaxListeners: 10, listenerCount: [Function] }
我之前*使用 require
模块做过这个,所以我可以复制它。但我想手动创建更多。我在这方面有一些问题:
- 是否可以手动复制它,在没有
require
的情况下进行硬编码? - 是否可以创建任何类型的属性,例如 getter 或 setter?
- 使用构造函数时是否可以创建这些“对象”之一?
提前致谢。
*或者我记得那个,我记性很差
已编辑:
需要明确的是:我不是在谈论 prototype
。例如,在我的示例中,您可以看到 defaultMaxListeners
不是来自原型(prototype)。在代码中:
EventEmitter.defaultMaxListeners // 10
EventEmitter.prototype.defaultMaxListeners // undefined
EventEmitter() //No error
最佳答案
- Is possible replicate this manually, harcoded without require? Is
- possible to create any type of property like getters or setters? Is
- posible to create one of these 'objects' when you use a constructor?
是
在JS中,函数也是对象。您可以像任何其他对象一样将属性附加到它们。此外,在 JS 中,函数既可以用作函数,也可以用作对象构造函数。
以下示例显示了您可以对函数执行的操作。我使用的是经典 OOP 术语,因为我不知道他们在 JS 中如何调用它们。
function SomeConstructor(){
this.instanceProperty = 'foo';
}
// Instance Method
SomeConstructor.prototype.method = function(){
console.log('method');
}
// Static Method
SomeConstructor.staticMethod = function(){
console.log('static');
}
var test = new SomeConstructor();
test.method();
SomeConstructor.staticMethod();
关于javascript - 混合数据类型、函数和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858125/