Object.defineProperty(obj,propertyName,{})
- 给对象添加属性(指定描述符)
- 设置对象属性的元属性
const person = {
firstName: "chen",
lastName: "guanxi",
};
// 定义对象的属性的属性(原属性)
Object.defineProperty(person, "fullname", {
// value:'chen guanxi', 属性的值
configurable: false, // 是否可以重新配置或者删除
// writable:true, // 是否可以枚举
enumerable: true, // 是否可以枚举,遍历, for in
get() {
// 属性读取时会调用的方法(返回值就是属性的值)
return this.firstName + " " + this.lastName;
},
set(newVal) {
// console.log(newVal); luo yonghao
// 利用数组一一对应关系来解构
const [firstName, lastName] = newVal.split(" ");
console.log(firstName); // luo
console.log(lastName); // yonghao
// console.log(this); { firstName: 'chen', lastName: 'guanxi', fullname: [Getter/Setter] }
this.firstName = firstName;
this.lastName = lastName;
},
});
// 此时会调用get方法
console.log(person.fullname); //chen guanxi
// 此时会调用set方法
person.fullname = "luo yonghao";
console.log(person);
// { firstName: 'chen', lastName: 'guanxi', fullname: [Getter/Setter] } 修改前
// { firstName: 'luo', lastName: 'yonghao', fullname: [Getter/Setter] } 修改后
Object.keys()
不会遍历原型链
- 返回一个所有元素为字符串的数组,其元素来自于从给定的object上面可直接枚举的属性。这些属性的顺序与手动遍历该对象属性时的一致。
// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
// getFoo is a property which isn't enumerable
var myObj = Object.create({}, {
getFoo: {
value: function () { return this.foo; }
}
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']
Object.values()
不会遍历原型链
- 返回一个给定对象自身的所有可枚举属性值的数组,值的顺序与使用for…in循环的顺序相同 ( 区别在于 for-in 循环枚举原型链中的属性 )。
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']
// array like object with random key ordering
// when we use numeric keys, the value returned in a numerical order according to the keys
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']
// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 'bar';
console.log(Object.values(my_obj)); // ['bar']
// non-object argument will be coerced to an object
console.log(Object.values('foo')); // ['f', 'o', 'o']
Object.prototype.hasOwnProperty()
- 所有继承了 Object 的对象都会继承到 hasOwnProperty 方法。这个方法可以用来检测一个对象是否含有特定的自身属性;和 in 运算符不同,该方法会忽略掉那些从原型链上继承到的属性。
const obj = {
a: 1,
};
obj.__proto__.b = 2;
console.log(Object.keys(obj)); // ["a"]
for (const key in obj) {
console.log(key); // a b
if (obj.hasOwnProperty(key)) {
console.log(key); // a
}
}
for (const key in obj) {
console.log(key); // a b
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(key); // a
}
}