题目描述
实现new,或者 new 的时候发生了什么?
mdn new 的定义
developer.mozilla.org/en-US/docs/…
The new keyword does the following things:
-
Creates a blank, plain JavaScript object.
-
Adds a property to the new object (proto) that links to the constructor function's prototype object
-
Properties/objects added to the construction function prototype are therefore accessible to all instances created from the constructor function (using new).
-
Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).
-
It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.
中文:
- 创建一个空的简单JavaScript对象(即{});
- 链接该对象(设置该对象的constructor)到另一个对象 ;
- 将步骤1新创建的对象作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
前置知识,需要了解下 prototype, proto
《JavaScript高级程序设计》里有比较详细的解释。
下边是示例代码,对应的原型图
function Foo(){ }
var foo = new Foo();
再看下题目,理解了原型链就可以根据描述直接写了
function newPolyfill(fn) {
var o = {}; // 第一步 创建空对象
o.__proto__ = fn.prototype; // 第二步 ,修改原型查找
var res = fn.apply(o,[].slice.call(arguments,1)) // 第三步,修改新对象中的this,返回执行后的结果
if( (typeof res === 'object' || typeof res === 'function') && res !== null) {
// 第四步 如果第三步中,返回了 对象 或者function,则直接返回 该结果
return res;
}
return o;
}
测试
var foo = function(name) { this.name = name;};
var kk = newPolyfill(foo,'坤坤')
// 输出
{name: '坤坤'}