面向对象的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.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值