原型模式

js中的原型是指prototype属性,该属性指向一个对象(原型对象),当函数创建时会自动为函数添加该属性,同时我们也可以为prototype所指向的对象添加属性和方法,在所有的函数实例对象中都可以访问到该属性指向对象下的内容,所以一般情况下我们添加的内容都是为实例所共享的,这也正是原型对象的用途。

初始化原型对象:

function Person(){
        this.married = false;
        Person.prototype.name = "lllin";
        Person.prototype.age = "24";
        Person.prototype.married = true;
    }

访问原型对象中的内容:

  在原型对象中默认拥有constructor属性,该属性指向函数本身。

var person1 = new Person();
var person2 = new Person();
person1.married = "donot know";

console.log(person1.name);//lllin
console.log(person2.name);//lllin
console.log(person1.constructor);//Person对象本身

同名属性的覆盖关系:

console.log(person1.married);//person1.married>this.married>Person.prototype.married

如何根据实例得到原型对象:

console.log(Person.prototype.isPrototypeOf(person1));//true,判断Person.prototype是否是person1的原型对象
console.log(Object.getPrototypeOf(person1));//得到person1的原型对象

判断属性存在于实例中还是原型对象中:

  hasOwnProperty判断是否是实例属性,in判断属性是否在对象中。

console.log(person1.hasOwnProperty("married"));//true
console.log(person1.hasOwnProperty("name"));//false

console.log("name" in person1);//true,无论属性在原型对象中还是在实例中都会返回true

/*true:属性存在原型中,false:属性存在实例中*/
function hasPrototypeProperty(object,name){
    return !object.hasOwnProperty(name)&&(name in object);
}
console.log(hasPrototypeProperty(person1,"name"));//true

如何获取原型对象属性或实例属性:

  Object.keys得到的是实例属性,原型对象Person.prototype的实例属性是["name", "age", "married"]

for(var prop in person1){
    console.log(prop);//married,name,age
}

var keys = Object.keys(person1);
var protokeys = Object.keys(Person.prototype);
console.log(keys);//["married"]
console.log(protokeys);//["name", "age", "married"]

 

posted @ 2017-03-13 16:06  Acmen、L  阅读(348)  评论(0编辑  收藏  举报