js温故而知新—面向对象的程序设计

来源:互联网 发布:板房保暖 知乎 编辑:程序博客网 时间:2024/04/29 15:00

1.访问器属性

//    访问器属性//    访问器不包含数据值:它们包含一对儿getter和setter函数(这两个函数都不是必须的),//        在读取访问器属性时,会调用getter函数,这个函数负责返回有效的值,setter负责传入值    var book={        _year:2004,        edition:1    }    Object.defineProperty(book,"year",{        get:function () {            return this._year;        },        set:function (newValue) {            if(newValue>2004){                this._year=newValue;                this.edition+=newValue-2004;            }        }    });    book.year=2006;    console.log(book.edition);//3

2.原型的动态性

function Person(){}Person.prototype={    name:"wky",    age:"19",    sayName:function () {        console.log(this.name);    }};var person=new Person();person.sayName();Person.prototype={    name:"wkyyc",    age:"30",    getName:function () {        consoele.log(this.name);    }};//person.sayName();person.getName();//error//详情:红宝书P157 图6-3