在JavaScript中模拟’new’运算符
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在JavaScript中模拟’new’运算符,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2554字,纯文字阅读大概需要4分钟。
内容图文
我尝试用这样的代码在JavaScript中模拟’new’运算符:
Function.method('new', function ( ) {
var objPrototype = Object.create(this.prototype);
var instance = this.apply(objPrototype, arguments);
return instance;
});
但是,为了涵盖所有情况,return语句应如下所示:
return (typeof instance === 'object' && instance ) || objPrototype;
现在进行测试:
var SomeClass = function (param1, param2) {
this.param1 = param1;
this.param2 = param2;
};
var test1 = String.new('test1'); //in this case, the "instance" variable is an object
var test2 = SomeClass.new('test1', 'test2'); // in this case, the "instance" variable is undefined
这正是“新”运算符的作用吗?还有什么案子可以解决吗?
解决方法:
11.2.2 The new Operator 07001 07002 07003 07004
The production NewExpression :
new
NewExpression is evaluated as follows:
- Let ref be the result of evaluating NewExpression.
- Let constructor be 07005(ref).
- If 07006(constructor) is not Object, throw a 07007 exception.
- If constructor does not implement the [[Construct]] internal method, throw a 07007 exception.
- Return the result of calling the [[Construct]] internal method on constructor, providing no arguments (that is, an empty list of arguments).
The production MemberExpression :
new
MemberExpression Arguments
is evaluated as follows:
- Let ref be the result of evaluating MemberExpression.
- Let constructor be 07005(ref).
- Let argList be the result of evaluating Arguments, producing an internal list of argument values (070010).
- If 07006(constructor) is not Object, throw a 07007 exception.
- If constructor does not implement the [[Construct]] internal method, throw a 07007 exception.
- Return the result of calling the [[Construct]] internal method on constructor, providing the list argList as the argument values.
在任何一种情况下,都正确遵循所有步骤:
var objPrototype = Object.create(this.prototype); // 1-4 1-5
var instance = this.apply(objPrototype, arguments); // 5 6
兴趣点是2.
The specification for [[construct]]指出:
When the [[Construct]] internal method for a Function object F is
called with a possibly empty list of arguments, the following steps
are taken:
- Let obj be a newly created native ECMAScript object.
. . .
- Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list
passed into [[Construct]] as args.- If 07006(result) is Object then return result.
- Return obj.
typeof obj为null返回“object”,而null不是对象.但是,由于null是一个假值,您的代码也可以按预期工作:
return (typeof instance === 'object' && instance ) || objPrototype;
内容总结
以上是互联网集市为您收集整理的在JavaScript中模拟’new’运算符全部内容,希望文章能够帮你解决在JavaScript中模拟’new’运算符所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。