《JavaScript高级程序设计》学习记录 [持续更新]

引用类型

-Math对象

Math.min( )、Math.max( )、Math.ceil( )、Math.floor( )、Math.round( )、Math.random( )、Math.abs( )

-randomNum传入最小数和最大数可返回随机数,chouqu定义数组,调用randomNum可以返回随机数组项

function randomNum(min,max){
    var maybe = max - min;
    return Math.floor(Math.random()*maybe) + min;
}

//从中抽取一个幸运项;
var chouqu = ['水杯','茶杯','电脑','电源线','数据线','华为9X','恒大冰泉','卫生纸'];
var chouquNum = chouqu[randomNum(0,chouqu.length-1)];
console.log(chouquNum);

-20190306

面向对象

-理解对象

要修改属性的特性,必须要用 Object.defineProperty()

是否能修改属性的值:writable:false/ture(默认)

var person = {};
Object.defineProperty(person,"name",{
    writable:false,
    value:"Nick"
};

不能从对象删除属性:configurable: false/ture(默认)

var person = {};
Object.defineProperty(person,"name",{
    configurable: false,
    value:"Nickolase"
}

读取属性时调用函数:get
写入属性值时调用函数:set
写defineProperty的时候必须同时定义get、set,缺少一个会忽略或者报错。

var book = {
    _year : 2015,
    edition : 1
};
Object.defineProperty(book,"year", {
    get: function () {
        return this._year;
    },
    set: function(newValue){
        if(newValue > 2015){
            this._year = newValue;
            this.edition += newValue - 2015;
        }
    }
});
book.year = 2019;
console.log(book.edition);

评论

暂无评论