那些年成为node攻城狮的路(六)

对象

  • 属性
  • 数据属性
    存在四个描述符:configurable(是否可以通过delete删除)、emunerable(是否可枚举)、writeable(是否可修改属性的值)、value(具体的值)
var person={age:20};//age属性writeable、configurable、enumerable(默认全为true)
Object.defineProperty(person,'name',{
//那么属性 writeable、configurable、enumerable(默认全为false)
value :'Lyf'
})
//--->由此所构建出来的对象name属性不可修改、删除、和枚举,不允许调用defineProperty;age属性可以删除、修改、枚举、可以多次调用defineProperty。
console.log(person);//{age:20}
person.name='Mx';
person.age=22;
console.log(person);//{age:22}
console.log(person.name);//Lyf
  • 访问器属性
    存在四个描述符:configurable、enumerable、get(写入时调用)、set(读取时调用)
var book ={_year:2004,edition:1}//_约定只能通过对象方法访问,描述符默认全为true
Object.defineProperty(book,'year',{
    enumerable:true,//默认描述符全为false
    get:function(){
        return this._year;
    },
    set :function(value){
        this._year=value;
        this.edition++
    }
});
book.year=2016;
console.log(book)
  • 一次定义多个属性
Object.defineProperties(book,{
name:{writable:true,value:'Lyf'}
age:{get:function(){}}
})
  • 读取属性特性
    Object.getOwnPropertyDescriptor(对象,属性);

  • 原型prototype

function Person(){
this.name;
}
Person.prototype.sayName=function(){
 console.log(this.name);
}
var p1=new Person('Lyf');
那些年成为node攻城狮的路(六)_第1张图片
原型-构造函数-实例.png

构造函数.prototype=原型对象
实例.protot=原型对象
原型对象.constructor=构造函数

var p1=new Person();
==>
var p1={};
p1.__proto__=Person.prototype;
Person.call(p1);
  • 原型链,原型中的方法被所有实例所共享,寻找共有方法或属性时采取就近原则
F1.prototype=F2; F2.prototype=F3;
F1.prototype.constructor=F1;    F2.prototype.constructor=F2;

hasOwnPrototype(name);返回true表明该name属于实例对象,返回false则表明该实例属于原型对象。

你可能感兴趣的:(那些年成为node攻城狮的路(六))