How can “new new Something” produce valid results in JavaScript?

大憨熊 提交于 2019-12-04 03:24:29

问题


I'm currently developing a JavaScript parser and study the ECMAScript 5.1 specification. Here's a question which puzzles me at the moment.

§ 11.2 Left-Hand-Side Expressions defines the following NewExpression production:

NewExpression :
    MemberExpression
    new NewExpression

If I read it correctly, then the NewExpression may be something like

new new Something

(Actually, any amount of news.)

This puzzles me completely. How could new Something potentialy return anything you could once again new? Is it possible at all?


回答1:


It is not common at all, but it is possible; a function that returns a function:

function baz(){}
function foo(){return baz}

new new foo() instanceof baz // true



回答2:


Take a look at section 13.2.2 [[Construct]] in the specification. More precisely, step 9 of the algorithm.

  1. If Type(result) is Object then return result.

Functions are objects, so if you return a function from a function and try to instantiate the latter function using new, you'll get back the former function, not a new object. But functions are also constructors, so you can new the returned function.

function bar() {}
function foo() { return bar; }
new foo === bar; // true



回答3:


I had to use new new when using an object as namespace. Though there will be a nicer way:

Instead of:

var Namespace = function() {
    var ClassFirst = this.ClassFirst = function() {
        this.abc = 123;
    }
    var ClassSecond = this.ClassSecond = function() {
        console.log("Cluttered way to access another class in namespace: ", new new Namespace().ClassFirst().abc);
        console.log("Nicer way to access a class in same namespace: ", new ClassFirst().abc);
    }
}

new new Namespace().ClassSecond()

Do this:

var Namespace = new function() {
    var ClassFirst = this.ClassFirst = function() {
        this.abc = 123;
    }
    var ClassSecond = this.ClassSecond = function() {
        console.log("Cluttered way to access another class in namespace: ", new Namespace.ClassFirst().abc);
        console.log("Nicer way to access a class in same namespace: ", new ClassFirst().abc);
    }
}

new Namespace.ClassSecond()

Not directly related to the question, but I was googling new new javascript, because it looked pretty ugly and wrong. This post can help to avoid this unneeded object creation for fellow new new Google'ers.



来源:https://stackoverflow.com/questions/26767788/how-can-new-new-something-produce-valid-results-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!