Javascript dynamically created functions in an object -


I'm just studying JavaScript and I had to face a problem related to scoping.

Here is the code

  function user (attribute) {for (in properties i) {(function () {this ['Receive' + i] = function () {Return Properties [i];};}) (); }} Var me = new user ({id: 54, name: 'oahu'}); Console.log (me.getName ()); Console.log (me.getId ());   

How do I want to work it out? It has two functions: getName and getId related to Object

How it works: It does two things as I want, but they are related to the window

:

  • I tried to remove the line from the function. 3. I do what I do, but now it returns name "ohau" twice, instead of returning id and names

  • I tried to use the work from the window , like the problem remains in the previous case - this is the name Gives twice.

    Question: What am I doing and how do I work it, as I want?

    Sorry for creating this post using a PS phone, for potential typo or formatting problems. Also, please forgive me your English skills.

    Try to understand why the following code works:

    < / P>

        

    Valid use of this statement with An example of one of these is edit:

    Let me explain the statement with more concise than the use of an Implemented Function Expression (IIFE)

    Edit: If the with keyword is not correct, then you are not bad it has some legitimate uses:


    The reason for this is that your code does not work, because each function has its own value it . So when you call function expression within loop for loop, the value of this inside the function is no longer your new object; it's window To solve that problem, you can do something like this:

      (function (i, self, support) {self ["receive" + i] = function () {return Prop [i];};} (I, this, attribute))   

    However using the statement with the statement is clear and fast, it is fast because you have the function No call Are not.

    Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -