组织js原型方法

时间:2012-04-12 20:32:33

标签: javascript methods prototype

在尝试了js的原型继承之后,我发现我并不认为必须在对象之外声明我的对象的方法:

function obj(){
  this.averyday='i\'m shuffle\'n';
  this.gibmo='dinero';
  this.pullOut='that\'s what she said lol';
}

obj.prototype.alertProp=function(){
    alert(this.averyday);
}
obj.prototype.alertProp2=function(){
    alert(this.gibmo);
}

所以我提出了一种将方法组织成一个命名空间的方法

obj.prototype.m={
    //i'm passing in the object instance so the mathods can have access to it's properties
    alertProp:function(that){
          alert(that.theObj.everyday);
    },
    alertProp2:function(that){
          alert(that.myObj.gibmo+' '+that.myObj.someVal); // alerts "dinero some other value to be use "
    }
} 
var myobj = new obj;

然后使用我只需调用方法并传入对象实例(如果方法需要修改对象的属性)

myobj.m.alertProp({theObj:myobj,someVal:'some other value to be use'}) //alerts "i'm shuffle'n"

所以这里有一些我注意到的专业人士:

优点:

1)将方法组织到一个集中区域。

2)仅访问对象的“原型”一次(实际上使用较少的代码)。

3)似乎更具可读性(至少对我而言)。

缺点:......这是我需要你帮助的地方,有人看到这样做有什么不妥吗?任何表现问题或我所概述的专业人士的任何错误等......?

也有人看到我可能没有看到或不明显的任何其他专业人士吗?

1 个答案:

答案 0 :(得分:1)

我发现它有点复杂,我喜欢这样做:

MyObject = function (options) {
   this.init(options);
};

MyObject.prototype = {
  /**
   * Documentation
   */
  variable1: null,

  init: function (options) {
    // do something with options.
  },

  alertVariable: function () {
    alert(this.variable1);
  }
};

所以你不必担心发送额外的参数,你只需要调用它。

---------------------------- EDIT ------------------ ---------------

好吧,我不知道我是否做对了,但经过一些阅读后我相信这会“修复构造函数”的意思。如果我创建这样的对象:

Foo = function () {
  // Do something
};

然后Foo.prototype.constructor == Foo,正如人们所期望的那样。 我的方法(感谢Raynos)的问题在于,当我这样做时:

Foo.prototype = {...};

我覆盖了所有Foo的原型,所以Foo.property.constructor != Foo,这不是我们所期望的!而不是我们Foo.property.constructor == Object.prototype.constructor

那么,我们如何解决它?

Foo.prototype = {
  constructor: Foo, // <-- FIXED!
  ...
};

Ta da!

(这有很大帮助:http://beej.us/blog/data/javascript-prototypes-inheritance/

相关问题