2013年7月7日 星期日

給 JavaScript 的 Class 新增方法 ( .method vs .prototype )

今天閱讀JavaScript,看到一個,給 類別 新增方法(method)的方式
除了使用 prototype 的方式之外,也可以利用 Class.method('方法名稱' , function(){}};



上網查了一下,在 stackoverflow 得到答案,如下:

發問者提出以下程式的差異


Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }

以下是該文章的回覆及範例程式(應該也是標準答案了)

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.


// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();




參考網址

沒有留言:

張貼留言