Javascript中函数对像属性和方法的三个层次

//here are three ways to implements the basic operation, each way is on the different level in function definition.
/*
* defines the operations in prototype
* usage:
  var op = new Operator(10, 20);
  op.operate('add');
*/
/*
function Operator(x, y) {
 this.x = x;
 this.y = y;
}

Operator.prototype.add = function() { 
 return this.x + this.y; 
}

Operator.prototype.subtract = function() {
 return this.x - this.y; 
}

Operator.prototype.multiply = function() {
 return this.x * this.y; 
}

Operator.prototype.divide = function() {
 return this.x / this.y; 
}

Operator.prototype.operate = function(operateclass) {
 return this[operateclass](this.x, this.y); 
}
*/

 

/**
* defines the operations in every object instance
* usage:
  var op = new Operateor(10, 20);
  op.operate('add');
*/
function Operator(x, y) {
 this.x = x;
 this.y = y;
 this.add = add;
 this.subtract = subtract;
 this.multiply = multiply;
 this.divide = divide;
 this.operate = operate;
}

function add() { 
 return this.x + this.y; 
}

function subtract() {
 return this.x - this.y; 
}

function multiply() {
 return this.x * this.y; 
}

function divide() {
 return this.x / this.y; 
}

function operate(operateclass) {
 return this[operateclass](this.x, this.y); 
}

 


/*
* defines the operations as attributes of the Function object
* usage:
  Operator.operate('add', 10, 20);
*/
/*
function Operator() {
}

Operator.add = function(x, y) {
 return x + y; 
}

Operator.subtract = function(x, y) {
 return x - y; 
}

Operator.multiply = function(x, y) {
 return x * y; 
}

Operator.divide = function (x, y) {
 return x / y; 
}

Operator.operate = function(operateclass, x, y) {
 checkArguments(arguments);
 return Operator[operateclass](x, y);
}

function checkArguments(args) {
 var actual = args.length;
 var expected = args.callee.length;
 if (actual != expected) {
  throw new Error("the expected count of arguments is not equal to the actual!");
 }
 return true; 
}
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值