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

前端 未结 3 2059
无人共我
无人共我 2021-01-12 21:30

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

3条回答
  •  悲哀的现实
    2021-01-12 22:11

    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.

提交回复
热议问题