iT邦幫忙

DAY 8
4

網頁開發五四三系列 第 9

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

  • 分享至 

  • xImage
  •  

說明,JavaScript 的 Class 新增方法的兩種方式差異
在閱讀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();

上一篇
PHP 函式呼叫也有匿名?
下一篇
MySQL 效能優化,針對 Limit
系列文
網頁開發五四三12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
fillano
iT邦超人 1 級 ‧ 2013-09-24 17:09:12

Class.method(name, func),看起來很像Douglas Crockford多年前寫的一篇文章中提到的一個語法sugar:
Classical Inheritance in JavaScript

shazi iT邦新手 4 級 ‧ 2013-09-24 18:22:52 檢舉

讚!!

我要留言

立即登入留言