给原型对象动态添加属性 [英] Dynamically add properties to the prototype object

查看:25
本文介绍了给原型对象动态添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将属性动态添加到函数原型对象的最佳方法(或者它是否是一个好主意).

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).

这是我想出来的:

['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.

大家有什么建议吗?

推荐答案

['foo', 'bar'].forEach(function (method) {
    String.prototype[method] = function () {
        resolve(method);
    };
});

function resolve(method) {
    alert(method);
}

("hello world").foo();
("hello world").bar();

这篇关于给原型对象动态添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆