【深入xx】五
深入理解JavaScript系列(5):强大的原型和原型链
http://www.cnblogs.com/TomXu/archive/2012/01/05/2305453.html
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="utf-8" /> <title></title></head><body> <script type="text/javascript"> var Calculator = function (decimalDigits, tax) { this.decimalDigits = decimalDigits; this.tax = tax; }; Calculator.prototype = { add: function (x, y) { return x + y; }, subtract: function (x, y) { return x - y; } }; alert((new Calculator()).add(1, 3)); </script></body></html><!DOCTYPE html><html lang="zh-CN"><head> <meta charset="utf-8" /> <title></title></head><body> <script type="text/javascript"> var Calculator = function (decimalDigits, tax) { this.decimalDigits = decimalDigits; this.tax = tax; }; Calculator.prototype = function () { var add = function (x, y) { return x + y; }; var subtract = function (x, y) { return x - y; }; return { add: add, subtract: subtract }; }(); alert((new Calculator()).add(1, 3)); </script></body></html><!DOCTYPE html><html lang="zh-CN"><head> <meta charset="utf-8" /> <title></title></head><body> <script type="text/javascript"> var BaseCaculator = function () { this.decimalDigits = 2; }; BaseCaculator.prototype.add = function (x, y) { return x + y; }; BaseCaculator.prototype.subtract = function (x, y) { return x - y; }; var Calculator = function () { this.tax = 5; }; //Calculator.prototype = new BaseCaculator(); Calculator.prototype = BaseCaculator.prototype; var calc = new Calculator(); alert(calc.add(1, 1)); alert(calc.decimalDigits); </script></body></html><!DOCTYPE html><html lang="zh-CN"><head> <meta charset="utf-8" /> <title></title></head><body> <script type="text/javascript"> function foo() { this.add = function (x, y) { return x + y; }; } foo.prototype.add = function (x, y) { return x + y + 10; }; Object.prototype.subtract = function (x, y) { return x - y; }; var f = new foo(); alert(f.add(1, 2)); alert(f.subtract(1, 2)); </script></body></html><!DOCTYPE html><html lang="zh-CN"><head> <meta charset="utf-8" /> <title></title></head><body> <script type="text/javascript"> Object.prototype.bar = 1; var foo = {goo: undefined}; alert(foo.bar); alert('bar' in foo); alert(foo.hasOwnProperty('bar')); alert(foo.hasOwnProperty('goo')); </script></body></html>TAG: