This article brings you a detailed analysis of JavaScript operator precedence (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.
Having been writing JavaScript for two years, I thought I would not fall into the trap of syntax, but in fact I was slapped in the face. Recently, a handsome guy in the product development team asked me to discuss a problem. Question, in order to make it easier for everyone to read, I have abstracted the model of this problem:
var provider = { test: { $get: function(){ return function anonymous(config){ }; } } }; var type = "test"; var config = {}; new provider[type].$get()(config);
Why does this
in function anonymous
point to # when the above statement is run? ##window instead of the new object created by
new. The first thing I thought when I heard this question was: Nani! How is it possible that
this in the constructor corresponding to the
new operator does not point to a newly created object instance? ? At that time, because I did not carefully abstract the problem from the business, I was actually a little confused. But when I thought about it carefully, what exactly did this sentence express?
Thinking
Before talking about the meaning of this expression, let me tell you a few little things about the new operator:Return of constructor
The JavaScript constructor can return a value or not, for example:function Person(){ } var person = new Person()
this in the constructor. But when your constructor has a return value, you have to differentiate based on the situation. If a non-reference type value is returned, what is actually returned is still a newly created instance object. But when a value of a reference type is returned, the reference object itself is returned. For example:
function Person(){ return function(){} } var person = new Person() typeof person // "function"
Two forms of new operator
In fact, in MDN’s new operator description, the syntax isnew constructor[([arguments])]
After understanding the above steps, we are close to the essence of the problem. How does the JavaScript engine parse the expression
new provider[type].$get()(config);
(new provider[type].$get())(config);
new (provider[type].$get())(config);
var str = "Hello" + true ? "World" : "JavaScript";
Because the operator priority is higher than the conditional operator, adding parentheses at this time will make your code easier to read. Second, stay in awe of technology. The biggest fear is that you think you know it all, but in fact you know nothing.
The above is the detailed content of Detailed analysis of JavaScript operator precedence (with examples). For more information, please follow other related articles on the PHP Chinese website!