Object对象方法(九)create

132 阅读1分钟

javaScript Object对象方法create

作用:用于创建一个新的对象的原型,使新创建的对象的原型为参数传入的对象

一、基本用法

const obj1 = {
  age: 18,
  name: 'zg',
  study: function() {
    console.log("i am study");
  },
  friends: ['lucy', 'jam']
};
let obj2 = Object.create(obj1, {
  age: {
    writable: true,
    enumerable: true,
    value: 66
  }
});
console.log(obj2);
/** 结果
{
    "age": 66
}
*/
console.log(obj2.__proto__);
/** 结果
{
    "age": 18,
    "name": "zg",
    "friends": [
        "lucy",
        "jam"
    ]
}
*/

二、当对象为null的场景

传null值的时候,会产生很多不可预期的行为,因为它不会在Object.prototype继承任何对象方法,因此很可能在调试的时候出现错误

const obj3 = Object.create(null, {
  age: {
    writable: true,
    enumerable: true,
    value: 66
  },
  name: {
    writable: true,
    enumerable: true,
    value: "zg"
  }
});
console.log(obj3);
/** 结果
{
  "age": 66,
  "name": "zg"
}
*/
console.log(obj3.__proto__);
/** 结果
undefined
*/

三、传null与普通对象的差别

传null并不意味着就不好,反而有它存在的意义.当我们需要忽略/过滤掉一些原型上的方法时,传入null会是一个更好的选择,案例如下: 原型对象上的影响

const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
  return name in ages;
}

function getAge(name) {
  return ages[name];
}

console.log(hasPerson("hasOwnProperty")); 
/** 结果
true
*/
console.log(getAge("toString")); 
/** 结果
[Function: toString]
*/

使用create传入null之后,可以直接避免由于原型链上的属性值诱导.

const ages = Object.create(null);
function hasPerson(name) {
  return name in ages;
}

function getAge(name) {
  return ages[name];
}

console.log(hasPerson("hasOwnProperty")); 
/** 结果
false
*/
console.log(getAge("toString")); 
/** 结果
undefined
*/

四、继承的用法

function Person(age, name) {
  this.age = age;
  this.name = name;
}

function Student(uid) {
  this.uid = uid;
}
const person1 = new Person(18, 'zg');
Student.prototype = Object.create(Person.prototype);
console.log(Student.prototype);
/** 结果
Person {}
*/