(精华)2020年6月25日 JavaScript高级篇 对象属性

一:自有属性

// ----------实例属性,自有属性----------
var obj01 = {};
obj01.name = 'laney';
obj01.action = function () {
    console.log('function');
}
obj01['from'] = '中国';
Object.defineProperty(obj01, 'age', {
    configurable: true,
    enumerable: true, //可枚举
    value: "20",
    writable: true
});
//----------原型继承属性----------
var o2 = {};
o2.x = 1;
var p = Object.create(o2);
p.__proto__ === o2 //true
var k1 = Object.create(null); //无原型属性
var m2 = Object.create(Object.prototype); // m2 = {};
var m3 = Object.create(Object.prototype, {
    name: {
        value: 'alice',
        configurable: true
    }
});
//----------合并对象属性(新对象)----------
var ob01 = {
    name: '122',
    age: '10'
}
var ob02 = {
    age: '20'
}
var ob03 = {
    run: 'ok'
}
const copy = Object.assign({}, ob01, ob02, ob03); //从右到左合并
const copy2 = Object.assign(ob01, ob02, ob03); //从右到左合并
//----------删除对象属性----------
var onePerson = {
    age: '20',
    weight: 50,
    name: 'alice'
};
var otherPerson = Object.create(onePerson);
otherPerson.name = 'laney';
//删除delete ,只能删除实例属性,不能删除继承属性
delete otherPerson.name
delete otherPerson.weight
//----------判断属性来源----------
var flower = {
    name: '玫瑰',
    color: 'red'
};
var flower02 = Object.create(flower);
flower02.size = '20';
flower02.from = 'china';
Object.defineProperty(flower02, 'age', {
    // configurable: true,
    // enumerable: true,
    value: "20",
    writable: true
});
'name' in flower02 //true
    'size' in flower02 //true
flower02.hasOwnProperty('name') //false
flower02.hasOwnProperty('size') //true
//----------可枚举的实例属性----------
var keys = Object.keys(flower02); //实例属性 -  可以枚举的
var values = Object.values(flower02);
//实例属性 - 可以枚举和不可枚举
var p2 = Object.getOwnPropertyNames(flower02);
//前提是 定义必须可以枚举
for (var key in flower02) {
    console.log('------');
    console.log(key);
    console.log(flower02[key])
    // size,from,name,color  - 实例属性 继承
    // age  不可枚举 
}

二:访问器属性

var man = {
    name: "张三",
    age: 24,
    color: 'red'
};
var person1 = JSON.stringify(man); //序列化
var person2 = JSON.stringify(man, ["name", "age"]); //过滤
var person3 = JSON.stringify(man, ["name", "age"], 8); //格式化
var obj = {};
Object.defineProperty(obj, 'age', {
    configurable: false, //不能删除 
    writable: true, //能否修改 
    enumerable: true, //是否可枚举 
    value: 22
});
delete obj.age // false 不能删除 
obj.age = 30 //true 能修改
Object.defineProperties(obj, {
    name: {
        value: 'laney',
        writable: true,
        enumerable: true,
        configurable: true
    },
    age: {
        configurable: false, //不能删除 
        writable: false, //能否修改 
        enumerable: true, //是否可枚举 
        value: 22
    }
})
obj.age = 30
//访问器属性
var emp = {
    _name: 'laney',
    _age: '20'
};
Object.defineProperty(emp, 'otherName', {
    enumerable: true,
    configuration: true,
    get: function () {
        return this._name
    }
});
emp.otherName
emp.otherName = 'alise'; //不能修改, 因为没有set

你可能感兴趣的:(#,Javascript,高级篇)