原型模式

js中的原型是指prototype属性,该属性指向一个对象(原型对象),当函数建立时会自动为函数添加该属性,同时咱们也能够为prototype所指向的对象添加属性和方法,在全部的函数实例对象中均可以访问到该属性指向对象下的内容,因此通常状况下咱们添加的内容都是为实例所共享的,这也正是原型对象的用途。函数

初始化原型对象:this

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

访问原型对象中的内容:spa

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

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对象自己

同名属性的覆盖关系:code

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的原型对象

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

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

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"]io

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"]
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息