第25章 对象的新增方法

1 Object.defineProperty() 

直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。(定义属性

三个参数:属性所在的对象、属性的名字和一个描述符对象。

描述符对象中包含四个特性:configurable、enumerable、writable 和value。如果不指定,configurable、enumerable 和writable 特性的默认值都是false。两个方法:getter 和setter 函数,用于设置一个属性的值会导致其他属性发生变化

var person = {};
Object.defineProperty(person, 'name', {
    writable: true, // 1.能否修改属性的值
    value: 'Nicholas' // 2.属性的数据值
    // Enumerable:"true"//3.能否通过for-in 循环返回属性
});
console.log(person.name); // "Nicholas"
person.name = 'Greg'; // writable: false该行将会报错,即为只读属性
console.log(person.name); // "Greg"
 
var person = {};
Object.defineProperty(person, "name", {
    configurable: true,//4.能否通过delete 删除属性
    value: "Nicholas"
});
alert(person.name); //"Nicholas"
delete person.name;// configurable: false该行将会报错
alert(person.name); //undefined
//定义单个属性 
var book = {
    _year: 2004,
    edition: 1
};
Object.defineProperty(book, "year", {
    get: function(){
        return this._year;
    },
    set: function(newValue){
        if (newValue > 2004) {
            console.log(this);//{_year: 2004, edition: 1}
            this._year = newValue;
            this.edition += newValue - 2004;
        }
    }
});
book.year = 2005;
alert(book); //{_year: 2005, edition: 2}

2 Object.getOwnPropertyDescriptor()

可以取得给定属性的描述符返回对象某个属性描述对象。(读取属性

两个参数:属性所在的对象和要读取其描述符的属性名称。

//定义多个属性
var book = {};
Object.defineProperties(book, {
    _year: {
        value: 2004
    },
    edition: {
        value: 1
    },
    year: {
        get: function(){
            return this._year;
        },
        set: function(newValue){
            if (newValue > 2004) {
            this._year = newValue;
            this.edition += newValue - 2004;
            }
        }
    }
});
var descriptor = Object.getOwnPropertyDescriptor(book, '_year'); // 返回描述符对象
console.log(descriptor); // {value: 2004, writable: false, enumerable: false, configurable: false}
var descriptor2 = Object.getOwnPropertyDescriptor(book, 'year');
console.log(descriptor2); // {enumerable: false, configurable: false, get: ƒ, set: ƒ}

3 Object.getOwnPropertyDescriptors()--es6

3.1 基本用法

返回指定对象所有自身属性(非继承属性)的描述对象

const obj = {
  foo: 123,//字面量定义的属性,其他三个描述对象默认值为true
  get bar() { return 'abc' }
};
Object.getOwnPropertyDescriptors(obj)
// { foo:
//    { value: 123,
//      writable: true,
//      enumerable: true,
//      configurable: true },
//   bar:
//    { get: [Function: get bar],
//      set: undefined,
//      enumerable: true,
//      configurable: true } }

//该方法的实现非常容易
function getOwnPropertyDescriptors(obj) {
  const result = {};
  for (let key of Reflect.ownKeys(obj)) {
    result[key] = Object.getOwnPropertyDescriptor(obj, key);
  }
  return result;
}

3.2 常见用途

  • 拷贝对象中的方法
//该方法的引入目的,主要是为了解决Object.assign()无法正确拷贝get属性和set属性的问题。
const source = {
  set foo(value) {
    console.log(value);
  }
};
const target1 = {};
Object.assign(target1, source);//{foo: undefined}:这是因为Object.assign方法总是拷贝一个属性的值,而不会拷贝它背后的赋值方法或取值方法。
Object.getOwnPropertyDescriptor(target1, 'foo')
// { value: undefined,
//   writable: true,
//   enumerable: true,
//   configurable: true }

//配合Object.defineProperties()方法,就可以实现正确拷贝。
const source = {
  set foo(value) {
    console.log(value);
  }
};
const target2 = {};
Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source));
Object.getOwnPropertyDescriptor(target2, 'foo')
// { get: undefined,
//   set: [Function: set foo],
//   enumerable: true,
//   configurable: true }
// 或者
const shallowMerge = (target, source) => Object.defineProperties(
  target,
  Object.getOwnPropertyDescriptors(source)
);
  • 浅拷贝
//配合Object.create()方法,将对象属性克隆到一个新对象。这属于浅拷贝。
const clone = Object.create(Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj));
// 或者
const shallowClone = (obj) => Object.create(
  Object.getPrototypeOf(obj),
  Object.getOwnPropertyDescriptors(obj)
);
  •  继承
//可以实现一个对象继承另一个对象
//ES5
const obj = {
  __proto__: prot,
  foo: 123,
};
//ES6: 规定__proto__只有浏览器要部署,其他环境不用部署
const obj = Object.create(prot);
obj.foo = 123;
// 或者
const obj = Object.assign(
  Object.create(prot),
  {
    foo: 123,
  }
);
//或者
const obj = Object.create(
  prot,
  Object.getOwnPropertyDescriptors({
    foo: 123,
  })
);

4 Object.keys()和Object.getOwnPropertyNames()

Object.keys():接收一个对象作为参数返回一个包含所有可枚举属性的字符串数组
Object.getOwnPropertyNames():接收一个对象作为参数返回所有自身属性的属性名组成的数组(包括不可枚举属性但不包括Symbol值作为名称的属性)。

function Person(){ 
} 
Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer"; 
Person.prototype.sayName = function(){ 
 alert(this.name); //没有打印
}; 
var keys = Object.keys(Person.prototype); 
alert(keys); //[name,age,job,sayName] //原型对象上的属性
var keys2 = Object.getOwnPropertyNames(Person.prototype); 
alert(keys2); //[constructor,name,age,job,sayName"]//原型对象上的所有属性

var p1 = new Person(); 
p1.name = "Rob"; 
p1.age = 31; 
var p1keys = Object.keys(p1); 
alert(p1keys); //[name,age]//实例对象上的属性

5 Object.create()

指定对象为原型对象创建新的对象

var student = {
    school: '北京大学'
};
var stu = Object.create(student, {
    name: {
        value: '张三',
        writable: true,
        configurable: true,
        enumerable: true
    }
});
consle.log(stu);//{name: "张三"}
console.log(stu.__proto__ === student); //true:stu的原型对象为student
console.log(stu.school); //北京大学
for (var key in stu) {
    console.log(key); //name school
}

6 Object.is() --es6

  • ES5 比较两个值是否相等,只有两个运算符:相等运算符(==)和严格相等运算符(===)。它们都有缺点,前者会自动转换数据类型,后者的NaN不等于自身,以及+0等于-0
  • Object.is() 用来比较两个值是否严格相等,与严格比较运算符(===)的行为基本一致。
//同===
Object.is('foo', 'foo')// true
Object.is({}, {})// false
//不同于===
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

7 Object.assign()--es6

7.1 基本用法

用于对象的合并,将源对象(source)的所有可枚举属性(包括Symbol,但不包括继承的属性),复制到目标对象(target)。

第一个参数目标对象,如果该参数不是对象,则会先转成对象,然后返回;如果无法转成对象,就会报错。后面的参数都是源对象,这些参数都会转成对象,如果无法转成对象,就会跳过(字符串除外)

const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

//如果非对象参数出现在目标对象的位置
typeof Object.assign(2) // "object"
Object.assign(undefined) // 报错:由于undefined和null无法转成对象,所以如果它们作为参数,就会报错。
Object.assign(null) // 报错

//如果非对象参数出现在源对象的位置
let obj = {a: 1};
Object.assign(obj, undefined) === obj // true
Object.assign(obj, null) === obj // true
const v1 = 'abc';
const v2 = true;
const v3 = 10;
const obj = Object.assign({}, v1, v2, v3);
console.log(obj); // { "0": "a", "1": "b", "2": "c" }:除了字符串会以数组形式,拷贝入目标对象,其他值都不会产生效果。这是因为只有字符串的包装对象,会产生可枚举属性。
Object(true) // {[[PrimitiveValue]]: true}
Object(10)  //  {[[PrimitiveValue]]: 10}
Object('abc') // {0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"}

//只拷贝源对象的自身属性(不拷贝继承属性),也不拷贝不可枚举的属性(enumerable: false)
Object.assign({b: 'c'},
    Object.defineProperty({}, 'invisible', {
        enumerable: false,
        value: 'hello'
    })
)// { b: 'c' }

//属性名为 Symbol 值的属性,也会被Object.assign()拷贝
Object.assign({ a: 'b' }, { [Symbol('c')]: 'd' })// { a: 'b', Symbol(c): 'd' }

7.2 注意

(1)浅拷贝

如果源对象某个属性的值是对象,那么目标对象拷贝得到的是这个对象的引用。这个对象的任何变化,都会反映到目标对象上面。

const obj1 = {a: {b: 1}};
const obj2 = Object.assign({}, obj1);
obj1.a.b = 2;
obj2.a.b // 2

(2)同名属性的替换

如果目标对象与源对象有同名属性,则后面的属性会覆盖前面的属性。

const target = { a: 1, b: 1 };
const source1 = { b: 2, c: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

const target = { a: { b: 'c', d: 'e' } }
const source = { a: { b: 'hello' } }
Object.assign(target, source)// { a: { b: 'hello' } }

(3)数组的处理

会把数组视为对象

Object.assign([1, 2, 3], [4, 5])
// [4, 5, 3]:Object.assign()把数组视为属性名为 0、1、2 的对象,因此源数组的 0 号属性4覆盖了目标数组的 0 号属性1。

(4)取值函数的处理

如果要复制的值是一个取值函数,那么将求值后再复制

const source = {
  get foo() { return 1 }
};
const target = {};
Object.assign(target, source)// { foo: 1 }

7.3 常见用途

(1)为对象添加属性

class Point {
  constructor(x, y) {
    Object.assign(this, {x, y});//将x属性和y属性添加到Point类的对象实例
  }
}

 (2)为对象添加方法

Object.assign(SomeClass.prototype, {
  someMethod(arg1, arg2) {
    ···
  },
  anotherMethod() {
    ···
  }
});

// 等同于下面的写法
SomeClass.prototype.someMethod = function (arg1, arg2) {
  ···
};
SomeClass.prototype.anotherMethod = function () {
  ···
};

(3)克隆对象(包含继承属性)

//将原始对象拷贝到一个空对象,就得到了原始对象的克隆.采用这种方法克隆,只能克隆原始对象自身的值,不能克隆它继承的值。
function clone(origin) {
  return Object.assign({}, origin);
}
//如果想要保持继承链,可以采用下面的代码。
function clone(origin) {
  let originProto = Object.getPrototypeOf(origin);
  return Object.assign(Object.create(originProto), origin);
}

(4)合并多个对象

将多个对象合并到某个对象

const merge =
  (target, ...sources) => Object.assign(target, ...sources);

如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。

const merge =
  (...sources) => Object.assign({}, ...sources);

 (5)为属性指定默认值

由于存在浅拷贝的问题,DEFAULTS对象和options对象的所有属性的值,最好都是简单类型,不要指向另一个对象。否则,DEFAULTS对象的该属性很可能不起作用。

//生效
const DEFAULTS = {
  logLevel: 0,
  outputFormat: 'html'
};
function processContent(options) {
  options = Object.assign({}, DEFAULTS, options);
  console.log(options);
  // ...
}
//不生效
const DEFAULTS = {
  url: {
    host: 'example.com',
    port: 7070
  },
};
processContent({ url: {port: 8000} })
// {
//   url: {port: 8000}
// }

8 __proto__属性--es6

__proto__属性(前后各两个下划线),用来读取或设置当前对象的原型对象(prototype)。

__proto__前后的双下划线,说明它本质上是一个内部属性,而不是一个正式的对外的 API。因此,无论从语义的角度,还是从兼容性的角度,都不要使用这个属性,而是使用下面的Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作)、Object.create()(生成操作)代替。

// es5 的写法
const obj = {
  method: function() { ... }
};
obj.__proto__ = someOtherObj;

// es6 的写法
var obj = Object.create(someOtherObj);
obj.method = function() { ... };

如果一个对象本身部署了__proto__属性,该属性的值就是对象的原型

Object.getPrototypeOf({ __proto__: null })// null

9 Object.setPrototypeOf()--es6

Object.setPrototypeOf方法的作用与__proto__相同,用来设置一个对象的原型对象(prototype),返回参数对象本身

//格式
Object.setPrototypeOf(object, prototype)
//用法
const o = Object.setPrototypeOf({}, null);
//等于
function setPrototypeOf(obj, proto) {
  obj.__proto__ = proto;
  return obj;
}

let proto = {};
let obj = { x: 10 };
Object.setPrototypeOf(obj, proto);//proto对象设为obj对象的原型
proto.y = 20;
proto.z = 40;
obj.x // 10
obj.y // 20
obj.z // 40

//如果第一个参数不是对象,会自动转为对象。但是由于返回的还是第一个参数,所以这个操作不会产生任何效果。
Object.setPrototypeOf(1, {}) === 1 // true
Object.setPrototypeOf('foo', {}) === 'foo' // true
Object.setPrototypeOf(true, {}) === true // true

//由于undefined和null无法转为对象,所以如果第一个参数是undefined或null,就会报错。
Object.setPrototypeOf(undefined, {})// TypeError: Object.setPrototypeOf called on null or undefined
Object.setPrototypeOf(null, {})// TypeError: Object.setPrototypeOf called on null or undefined

10 Object.getPrototypeOf()--es6

用于读取一个对象的原型对象

function Rectangle() {
  // ...
}
const rec = new Rectangle();
Object.getPrototypeOf(rec) === Rectangle.prototype // true

Object.setPrototypeOf(rec, Object.prototype);
Object.getPrototypeOf(rec) === Rectangle.prototype// false

//如果参数不是对象,会被自动转为对象。
// 等同于 Object.getPrototypeOf(Number(1))
Object.getPrototypeOf(1)// Number {[[PrimitiveValue]]: 0}
// 等同于 Object.getPrototypeOf(String('foo'))
Object.getPrototypeOf('foo')// String {length: 0, [[PrimitiveValue]]: ""}
// 等同于 Object.getPrototypeOf(Boolean(true))
Object.getPrototypeOf(true)// Boolean {[[PrimitiveValue]]: false}

Object.getPrototypeOf(1) === Number.prototype // true
Object.getPrototypeOf('foo') === String.prototype // true
Object.getPrototypeOf(true) === Boolean.prototype // true

//如果参数是undefined或null,它们无法转为对象,所以会报错。
Object.getPrototypeOf(null)// TypeError: Cannot convert undefined or null to object
Object.getPrototypeOf(undefined)// TypeError: Cannot convert undefined or null to object

11 Object.keys() 

ES5 引入了Object.keys方法,返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键名

var obj = { foo: 'bar', baz: 42 };
Object.keys(obj)// ["foo", "baz"]

 ES2017 引入了跟Object.keys配套的Object.valuesObject.entries,作为遍历一个对象的补充手段,供for...of循环使用。

let {keys, values, entries} = Object;
let obj = { a: 1, b: 2, c: 3 };

for (let key of keys(obj)) {
  console.log(key); // 'a', 'b', 'c'
}

for (let value of values(obj)) {
  console.log(value); // 1, 2, 3
}

for (let [key, value] of entries(obj)) {
  console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
}

12 Object.values()--es6

Object.values方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值

//返回数组
const obj = { foo: 'bar', baz: 42 };
Object.values(obj)// ["bar", 42]

//遍历顺序
const obj = { 100: 'a', 2: 'b', 7: 'c' };
Object.values(obj)// ["b", "c", "a"]:返回数组的成员顺序,与本章的《属性的遍历》部分介绍的排列规则一致

//可遍历的
const obj = Object.create({}, {p: {value: 42}});
Object.values(obj) // []:第二个参数添加的对象属性(属性p),如果不显式声明,默认是不可遍历的,因为p的属性描述对象的enumerable默认是false

const obj = Object.create({}, {p:
  {
    value: 42,
    enumerable: true
  }
});
Object.values(obj) // [42]:把enumerable改成true,Object.values就会返回属性p的值。

Object.values({ [Symbol()]: 123, foo: 'abc' });
// ['abc']:Object.values会过滤属性名为 Symbol 值的属性。

//参数为字符串
Object.values('foo')
// ['f', 'o', 'o']:参数是一个字符串,会返回各个字符组成的一个数组。字符串会先转成一个类似数组的对象
//参数为数字和布尔
Object.values(42) // []:如果参数不是对象,Object.values会先将其转为对象。由于数值和布尔值的包装对象,都不会为实例添加非继承的属性。所以,Object.values会返回空数组。
Object.values(true) // []

13 Object.entries()--es6

13.1 基本用法

Object.entries()方法返回一个数组,成员是参数对象自身的(不含继承的)所有可遍历(enumerable)属性的键值对数组。

//返回数组
const obj = { foo: 'bar', baz: 42 };
Object.entries(obj)// [ ["foo", "bar"], ["baz", 42] ]

Object.entries({ [Symbol()]: 123, foo: 'abc' });
// [ [ 'foo', 'abc' ] ]:如果原对象的属性名是一个 Symbol 值,该属性会被忽略。

 13.2 常见用途

  • 遍历对象的属性

let obj = { one: 1, two: 2 };
for (let [k, v] of Object.entries(obj)) {
  console.log(
    `${JSON.stringify(k)}: ${JSON.stringify(v)}`
  );
}
// "one": 1
// "two": 2
  •  对象转为真正的Map结构
const obj = { foo: 'bar', baz: 42 };
const map = new Map(Object.entries(obj));
map // Map { foo: "bar", baz: 42 }

14 Object.fromEntries()--es6

14.1 基本用法

Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象

Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])// { foo: "bar", baz: 42 }

14.2 常见用途

  •  Map 结构转为对象
// 例一
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42]
]);
Object.fromEntries(entries)
// { foo: "bar", baz: 42 }

// 例二
const map = new Map().set('foo', true).set('bar', false);
Object.fromEntries(map)// { foo: true, bar: false }
  • 查询字符串转为对象
//配合URLSearchParams对象,将查询字符串转为对象。
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
// { foo: "bar", baz: "qux" }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值