仅向某个对象添加功能

时间:2012-07-29 04:22:22

标签: javascript function object

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

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作为例子,但我还需要学习所有其他的东西。谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的对象需要私有方法。在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");无法访问。