// 1.创建一个空对象
// 2.将空对象的原型设置为proto
// 3.将属性挂载到空对象身上
// 4.返回对象
// create 、 new 、instanceof 左侧都是对象, new和instanceof右侧是构造函数、Class声明的类, create右侧是新创建对象的原型对象,是个对象
Object.my_create = function(proto, defineProperties){
// class Student{}
// var people = {}
// function Animial(){}
if(typeof proto !== 'object' || typeof proto !== 'function'){
throw new TypeError(`Object prototype may only be an Object or null: ${proto}`)
}
if ( defineProperties === null ) {
throw new TypeError('Cannot convert undefined or null to object')
}
const obj = {};
// Object.setPrototypeOf 是设置一个对象的原型
// obj.__proto__ = proto // 不建议这么做了
// 通常,应该使用 Object.setPrototypeOf() 方法来设置对象的原型。
Object.setPrototypeOf(obj, proto);
Object.defineProperties(obj, defineProperties);
return obj;
}
class Student{}
var people = {}
function Animial(){}
console.log(typeof Animial);
前端手撕代码——手撕Object.create()
最新推荐文章于 2024-09-14 22:18:26 发布