//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;
}
*/
三种实现运算的方法
本文介绍了三种不同的方式来实现基本的数学运算,包括加法、减法、乘法和除法。这三种方式分别是在原型中定义操作、在每个对象实例中定义操作以及将操作作为Function对象的属性进行定义。每种方法都有其特定的应用场景和优缺点。

被折叠的 条评论
为什么被折叠?



