代码改变世界

深入理解JavaScript系列阅读笔记(5):强大的原型和原型链

2013-04-06 08:15  极乐鸟  阅读(353)  评论(0编辑  收藏  举报

如何将其他对象设置到某个对象的原型上:

声明一个对象

var BaseCalculator = function(){
    this.decimaldigits = 2;
};
BaseCalculator.prototype = {
    add:function(x,y){
        return x + y;
    },
    sub:function(x,y){
        return x - y;
    }
}

我们再来声明另一对象

var Calculator = function(){
    this.tax = 2;
};

如果要将BaseCalculator对象设置Calsulator的原型上有两种方式:

1. Calculator.prototype = new BaseCalculator();//因为Calculator的原型是指向BaseCalculator的实例上的,所以可以访问他的decimalDigits属性值

2. Calculator.prototype = BaseCalculator.prototype;//将BaseCalculator的原型赋给Calculator的原型,在Calculator的实例上访问不到那个decimalDigits值了

重写原型时,重写的代码需要放在最后,这样才能覆盖前面的代码。

当检查对象上某个属性是否存在时,hasOwnProperty 是唯一可用的方法。同时在使用 for in loop 遍历对象时,推荐总是使用 hasOwnProperty 方法,这将会避免原型对象扩展带来的干扰。

JavaScript 不会保护 hasOwnProperty 被非法占用,因此如果一个对象碰巧存在这个属性,就需要使用外部的 hasOwnProperty 函数来获取正确的结果:

var foo = {
    hasOwnProperty:function(){
        return false;
    },
    hello:"hello"
};
foo.hasOwnProperty("hello");//总是返回false

// 使用{}对象的 hasOwnProperty,并将其上下为设置为foo
{}.hasOwnProperty.call(foo,'bar');