强大的原型和原型链

作者 | 汤姆大叔
前言
原型
var decimalDigits = 2,tax = 5;function add(x, y) {return x + y;}function subtract(x, y) {return x - y;}//alert(add(1, 3));
原型使用方式1:
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));
原型使用方式2:
Calculator.prototype = function () { } ();Calculator.prototype = function () {add = function (x, y) {return x + y;},subtract = function (x, y) {return x - y;}return {add: add,subtract: subtract}} ();//alert((new Calculator()).add(11, 3));
再来一点
分步声明:
var BaseCalculator = function () {//为每个实例都声明一个小数位数this.decimalDigits = 2;};//使用原型给BaseCalculator扩展2个对象方法BaseCalculator.prototype.add = function (x, y) {return x + y;};BaseCalculator.prototype.subtract = function (x, y) {return x - y;};
var BaseCalculator = function() {this.decimalDigits = 2;};BaseCalculator.prototype = {add: function(x, y) {return x + y;},subtract: function(x, y) {return x - y;}};
var Calculator = function () {//为每个实例都声明一个税收数字this.tax = 5;};Calculator.prototype = new BaseCalculator();
var calc = new Calculator();alert(calc.add(1, 1));//BaseCalculator 里声明的decimalDigits属性,在 Calculator里是可以访问到的alert(calc.decimalDigits);
var Calculator = function () {this.tax= 5;};Calculator.prototype = BaseCalculator.prototype;
var calc = new Calculator();alert(calc.add(1, 1));alert(calc.decimalDigits);
重写原型:
//覆盖前面Calculator的add() functionCalculator.prototype.add = function (x, y) {return x + y + this.tax;};var calc = new Calculator();alert(calc.add(1, 1));
原型链
function Foo() {this.value = 42;}Foo.prototype = {method: function() {}};function Bar() {}// 设置Bar的prototype属性为Foo的实例对象Bar.prototype = new Foo();Bar.prototype.foo = 'Hello World';// 修正Bar.prototype.constructor为Bar本身Bar.prototype.constructor = Bar;var test = new Bar() // 创建Bar的一个新实例// 原型链test [Bar的实例]Bar.prototype [Foo的实例]{ foo: 'Hello World' }Foo.prototype{method: ...};Object.prototype{toString: ... /* etc. */};
属性查找:
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)); //结果是3,而不是13alert(f.subtract(1, 2)); //结果是-1
function Foo() {}Foo.prototype = 1; // 无效
hasOwnProperty函数:
// 修改Object.prototypeObject.prototype.bar = 1;var foo = {goo: undefined};foo.bar; // 1'bar' in foo; // truefoo.hasOwnProperty('bar'); // falsefoo.hasOwnProperty('goo'); // true
var foo = {hasOwnProperty: function() {return false;},bar: 'Here be dragons'};foo.hasOwnProperty('bar'); // 总是返回 false// 使用{}对象的 hasOwnProperty,并将其上下为设置为foo{}.hasOwnProperty.call(foo, 'bar'); // true
// 修改 Object.prototypeObject.prototype.bar = 1;var foo = {moo: 2};for(var i in foo) {console.log(i); // 输出两个属性:bar 和 moo}
// foo 变量是上例中的for(var i in foo) {if (foo.hasOwnProperty(i)) {console.log(i);}}
总结

评论
