面向對象的Javascript,創建靜態方法和實例方法

轉自:http://blog.anselmbradford.com/2009/04/09/object-oriented-javascript-tip-creating-static-methods-instance-methods/

Object-Oriented JavaScript Tip: Creating static methods, instance methods

 

Custom JavaScript objects can have instance methods (function that are associated with a particular JavaScript object), but like other Object-Oriented languages, they can also have staticmethods, that is functions that are associated with the JavaScript class that created an object, as opposed to the object itself. This is useful in cases where a function (a.k.a. a method) will not be different in different object instances. Let’s look at an example…

Suppose you created a class to handle simple arithmetic calculations:

function Calculator() { }

To begin with, an instance method could be added to this class in one of two ways, either inside the constructor or through the class prototype. In this example, one method called multiply will be created, which returns the product of two values multiplied together. First, implemented in the constructor it looks like:

function Calculator() { this.multiply = function(val1 , val2) { return (val1*val2); } }

Via the class prototype, which is a more readable solution in my opinion, it would look like:

function Calculator() { } Calculator.prototype.multiply = function(val1 , val2) { return(val1*val2); }

Use of this method would then occur through instances of the Calculator class, like so:

var calc = new Calculator(); alert( calc.multiply(4,3) ); //pop-up alert with product of 4 times 3

However, it shouldn’t really be necessary to create an object to use the multiply method, since the method isn’t dependent on the state of the object for its execution. The method can be moved to the class to clean up this code a bit. First the class definition is created, which looks almost identical to the instance method declaration above, with the exception of the prototypekeyword being removed:

function Calculator() { } Calculator.multiply = function(val1 , val2) { return(val1*val2); }

Now the multiply method can be called through the class itself, instead of an instance of the class, like so:

alert( Calculator.multiply(4,3) ); //pop-up alert with product of 4 times 3

This entry was posted on Thursday, April 9th, 2009 at 5:52 am and is filed under JavaScript, Tips. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

 

發佈了17 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章