new的实现原理:
new 运算符是创建一个自定义对象或者具有构造函数的内置对象的实例
function new(func) {
// 创建一个新对象
lat target = {};
// 新对象继承了func原型上的属性
target.__proto__ = func.prototype;
// 将构造函数的作用域赋值给新对象
let res = func.call(target);
// 如果函数没有返回其他对象、方法,则返回新对象。
if (typeof(res) == "object" || typeof(res) == "function") {
return res;
}
return target;
}
let F = function () {
this.name = "小路"
}
F.prototype.count = 5
let fn1 = new F()
console.log(F.prototype)
console.log(fn1)
new出来的fn1继承了构造函数F上的方法和原型链上属性。
Object.create的实现原理:
Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
Object.create = function (o) {
// 创建新函数
var F = function () {};
// 函数原型指向传入值
F.prototype = o;
// 通过new实现
var newObj=new F();
return newObj;
};
let F = function () {
this.name = "小路"
}
F.prototype.count = 5
let fn2 = Object.create(F)
console.log(fn2)
Object.create()能继承原型上的属性,且创建出一个空的对象或者方法。
Object.create()第二个值则是要添加到新创建对象的可定义其可枚举属性或修改的属性描述符的对象。
let fn2 = Object.create(F, {
p: {
//初始值默认为 undefined.
value: 6,
// 可赋值(改)
writable: true,
// 可枚举
enumerable: true,
// 可配置(删除)
configurable: true
}
})