六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 35|回复: 0

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

[复制链接]

升级  20%

2

主题

2

主题

2

主题

童生

Rank: 1

积分
10
 楼主| 发表于 2013-1-29 09:27:46 | 显示全部楼层 |阅读模式
//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; 
}
*/
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表