可能是 JavaScript 中最难理解的部分,位于原型链旁边。
所以问题是:如何...
new dataObj(args);
...实际上创建一个对象,并定义它的原型链/构造函数/等?
最好是展示一个替代方案,以充分理解这个关键字。
The new
操作员使用内部[[Construct]] http://es5.github.com/#x13.2.2方法,它基本上执行以下操作:
- 初始化一个新的本机对象
- Sets the internal
[[Prototype]]
of this object, pointing to the Function prototype
property.
- 如果函数的
prototype
属性不是对象(原始值,例如数字、字符串、布尔值、未定义或空),Object.prototype
被用来代替。
- 创建对象后,它调用该函数,提供该对象作为其对象
this
value.
- 如果被调用函数的返回值是原语,则返回内部创建的对象。
- 否则,如果返回一个对象,那么内部创建的对象就会丢失。
一个等效的实现new
运算符确实如此,可以这样表达(假设 ECMAScript 5Object.create
方法可用):
function NEW(f) {
var obj, ret, proto;
// Check if `f.prototype` is an object, not a primitive
proto = Object(f.prototype) === f.prototype ? f.prototype : Object.prototype;
// Create an object that inherits from `proto`
obj = Object.create(proto);
// Apply the function setting `obj` as the `this` value
ret = f.apply(obj, Array.prototype.slice.call(arguments, 1));
if (Object(ret) === ret) { // the result is an object?
return ret;
}
return obj;
}
// Example usage:
function Foo (arg) {
this.prop = arg;
}
Foo.prototype.inherited = 'baz';
var obj = NEW(Foo, 'bar');
obj.prop; // 'bar'
obj.inherited; // 'baz'
obj instanceof Foo // true
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)