仅向某个对象添加函数

Adding a function to only a certain object

本文关键字:添加 函数 对象      更新时间:2024-04-29

我需要一个函数来只为给定的对象工作。我不确定这是否可能,但我尝试了一些类似的东西:

var a = {
    b: function(a) {
        return display(a)
    }
}
a.prototype.display = function(a) {
    return a;
}
alert(a.b('Hi'))​//This is suppose to work
alert(display(a))//This isn't suppose to work

但这不起作用,不知道为什么。我对原型有点陌生。例如,我在String.prototype中使用了它,但我还需要学习其他所有东西。谢谢你的帮助。

您需要在对象中使用一个私有方法。在javascript中实现这一点的唯一方法是关闭函数,并在当前对象的上下文中执行它。

var a = (function () {
      var display = function (a) {
          return a;
      };
      return {
         b : function(a) {
             // display exist in closure scope of b;
             //executing display in the context of current object
             return display.apply(this, arguments);
         }
      };
})();

此处display在外部无法访问。

alert(a.b("hi")); //will return hi

a.display("hi");不可访问。