动态添加原型对象的属性 [英] Dynamically add properties to the prototype object
本文介绍了动态添加原型对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道动态添加属性到函数的原型对象的最佳方法(或者甚至是一个好主意)。
I was wondering the best way to dynamically add properties to the prototype object of a function (or if it's even a good idea).
这就是我来的($ {
$ b
This is what I came up with:
['foo', 'bar'].forEach(function(method) {
String.prototype[method] = resolve;
});
function resolve() {
// Who the hell called me?
}
'str'.foo();
我正在调用相同的函数 resolve()
对于我添加的所有新属性,我需要检查谁调用了这个函数(该属性名称),以便根据该信息来计算一个实现。
这一切都是好奇的事情,我正在对疯狂的JavaScript API实现做一些测试。
I'm calling the same function resolve()
for all the new properties I've added and I need to check who called the function (which property name) in order to figure an implementation based on that information.
It's all a matter of curiosity, I'm doing some tests on crazy JavaScript API implementations.
你们有什么建议吗? >
Do you guys have any suggestions for this?
推荐答案
['foo', 'bar'].forEach(function (method) {
String.prototype[method] = function () {
resolve(method);
};
});
function resolve(method) {
alert(method);
}
("hello world").foo();
("hello world").bar();
这篇关于动态添加原型对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文