p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Professional JavaScript for Web Developers 3rd edition (http://p2p.wrox.com/forumdisplay.php?f=669)
-   -   Problem With Constructors (http://p2p.wrox.com/showthread.php?t=95085)

dysonlu October 6th, 2015 02:55 AM

Problem With Constructors
 
In chapter 6, the author explains that the constructor

function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}

is logically equivalent to this:

function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = new Function("alert(this.name)"); //logical equivalent
}

But he very briefly mentions that "creating a function in this manner is different with regard to scope chains and identifier resolution".

I do not understand what he meant by that. Can anyone explain?

Thanks much!
Dyson

lewisje November 10th, 2015 02:25 PM

It means that the Function constructor always creates functions in the global scope, while a function expression inside another function creates a function in that other function's inner scope; they're logically equivalent because alert is a global function and this is determined by execution context, not scope.

If the second example had created a variable named "alert" inside the outer function then the "alert" inside that Function constructor would still refer to the global alert.

If the first example had created a variable named "alert" inside the outer function then the "alert" inside that inner function expression would refer to the variable, and not the global alert.

dysonlu November 10th, 2015 02:33 PM

Thank you very much. I did not know that functions created with Function constructor always exist in the global scope.


All times are GMT -4. The time now is 02:10 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.