标签:
/* var answer = 0;//代码味太浓,不在局部作用域意味着可以在程序的任何部分被修改 function addNumbers(num1, num2) { answer = num1 + num2; } //每个函数都是孤立的存在于全局作用域内,污染了全局作用域 function subtractNumbers(num1, num2) { answer = num1 - num2; } function multiplyNUmbers(num1, num2) { answer = num1 * num2; } function divideNumbers(num1, num2) { if (num2 != 0) { answer = num1 / num2; } else { answer = 0; } } addNumbers(1, 2); alert(answer); subtractNumbers(1, 2); alert(answer); multiplyNUmbers(1, 2); alert(answer); divideNumbers(1, 2); alert(answer); */ function NumberFunctions() {//面向对象,有良好的结构,便于理解 var answer = 0; } NumberFunctions.prototype.addNumbers = function(num1, num2) { this.answer = num1 + num2; } NumberFunctions.prototype.subtractNumbers = function(num1, num2) { this.answer = num1 - num2; } NumberFunctions.prototype.multiplyNUmbers = function(num1, num2) { this.answer = num1 * num2; } NumberFunctions.prototype.divideNumbers = function(num1, num2) { if (num2 != 0) { this.answer = num1 / num2; } else { this.answer = 0; } } NumberFunctions.prototype.toString = function() {//创建的对象自动调用该方法 return this.answer; } var nf = new NumberFunctions(); nf.addNumbers(2, 1); alert(nf);//nf自动调用了toString()方法 nf.subtractNumbers(10, 3); alert(nf); nf.multiplyNUmbers(4, 5); alert(nf); nf.divideNumbers(12, 6); alert(nf); /* 其优点如下: 1)没有对全局作用域的污染,因为有NumberFunctions函数; 2)所有函数实际上都是NumberFunctions类的成员,因此构造了一个清晰的关系; 3)基本的面向对象:数据和操作数据的函数都封装得很好*/
标签:
原文地址:http://www.cnblogs.com/feile/p/5400444.html