Object.create() 引出的所有原型链相关的知识

493 阅读1分钟

定义

首先要知道Object.create()的定义 MDN 是这么定义的:

Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的 proto_。 Object.create(proto[, propertiesObject])

proto 新创建对象的原型对象。

let newO = Object.create(protoObj) ;

那么 newO._proto_ = protoObj;

原型链图

function Student(name) {
    this.name = name;
    this.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
}

var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!

手写Object.create()

if (typeof Object.create !== "function") {
    Object.create = function (proto, propertiesObject) {
        if (typeof proto !== 'object' && typeof proto !== 'function') {
            throw new TypeError('Object prototype may only be an Object: ' + proto);
        } else if (proto === null) {
            throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
        }

        if (typeof propertiesObject !== 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");

        function F() {}
        F.prototype = proto;

        return new F();
    };
}

寄生组合式继承

function inheritPrototype(subType, superType) {
    // 创建对象,创建父类原型的一个副本
    var prototype = Object.create(superType.prototype); 
    // 增强对象,弥补因重写原型而失去的默认的constructor 属性
    prototype.constructor = subType; 
    // 指定对象,将新创建的对象赋值给子类的原型
    subType.prototype = prototype; 
}

new 手写

function newFunc(){
	let newObj = {};
    let [constructor, args] = [...arguments];
    // newObj.__proto__ = constructor.prototype; 但是__proto__ 有兼容性
    newObj = Object.create(constructor.prototype);
    let result = fn.apply(newO, args);
    if(result && typeof result === 'object' || typeof result === 'function') {
    	return result;
    }
    return newObj;
}

instanceof

function isProto(leftVal, rightVal) {
	if(!leftVal || typeof leftVal !== 'object') return false;
    let leftProto = leftVal.__proto__;
    let rightProto = rightVal.prototype;
    while(leftProto) {
    	if(leftProto === rightProto) {
         	return true;
        }
        leftProto = leftProto.__proto__;
    }
    rturn false;
}