原型和原型链 复习

原型

function Person(){
    }

Person.prototype.name = 'Jim';
Person.prototype.sayName = function(){
    comsole.log(this.name);
};

var person1 = new Person();        
var person2 = new Person();          

下图说明了Person构造函数、Person原型以及person两个实例的关系。
要说明的是当构造函数创建一个新实例后,生成的实例会包含一个[[prototype]]指针,指向构造函数的原型对象。在chrome、Safari、Firefox中以proto形式存在;在其他实现中脚本是不可见的。

图片

原型使用方式扩展1

function Person(){
    }

Person.prototype = {
    name 'Jim'
    sayNamefunction(){
        comsole.log(this.name);
    }
} ;

原型使用方式扩展2

封装私有的function,通过return的形式暴露出简单的使用名称,以达到public/private的效果。

function Person(){
    }

Person.prototype = function(){
    name = 'Jim';

    sayName = function(){
        comsole.log(this.name);
    };

    return {
                name: name,
                sayName: sayName
    }
} ();

原型链

        function SuperType(){
            this.property = true;
        }

        SuperType.prototype.getSuperValue = function(){
            return this.property;
        };

        function SubType(){
            this.subproperty = false;
        }

        //inherit from SuperType
        SubType.prototype = new SuperType();

        SubType.prototype.getSubValue = function (){
            return this.subproperty;
        };

        var instance = new SubType();
        alert(instance.getSuperValue());   //true

        alert(instance instanceof Object);      //true
        alert(instance instanceof SuperType);   //true
        alert(instance instanceof SubType);     //true

        alert(Object.prototype.isPrototypeOf(instance));    //true
        alert(SuperType.prototype.isPrototypeOf(instance)); //true
        alert(SubType.prototype.isPrototypeOf(instance));   //true

关系图如下:

关系图

属性查找

当查找一个对象的属性时,JavaScript 会向上遍历原型链,直到找到给定名称的属性为止,到查找到达原型链的顶部 - 也就是 Object.prototype - 但是仍然没有找到指定的属性,就会返回 undefined。

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,而不是13
alert(f.subtract(1, 2)); //结果是-1

hasOwnProperty函数

hasOwnProperty是Object.prototype的一个方法,它可是个好东西,他能判断一个对象是否包含自定义属性而不是原型链上的属性,因为hasOwnProperty 是 JavaScript 中唯一一个处理属性但是不查找原型链的函数。

// 修改Object.prototype
Object.prototype.bar = 1; 
var foo = {goo: undefined};

foo.bar; // 1
'bar' in foo; // true

foo.hasOwnProperty('bar'); // false
foo.hasOwnProperty('goo'); // true

只有 hasOwnProperty 可以给出正确和期望的结果,这在遍历对象的属性时会很有用。 没有其它方法可以用来排除原型链上的属性,而不是定义在对象自身上的属性。


感谢@汤姆大叔 的《深入理解JavaScript系列》指导我学习!



blog comments powered by Disqus

Published

23 February 2014

Category

JavaScript

Tags