The problem of mutual access between JS object literal attributes and the relationship between this problem and the execution environment

Source: Internet
Author: User

An issue that cannot be accessed between object literal attributes:

I used to try to reuse some properties when I was defining an object, and for the sake of reusability:

// Test 1 var person = {    firstName    "Bill",    lastName    "Gates",    FullName    + "" + lastName        //  error here }alert (person.firstname); alert ( person.lastname); alert (person.fullname);  

The result is that this reuse results in an error: "Referenceerror:firstname is not defined", firstName undefined (not present).

But try to comment on the error line to see if the firstName is present:

// Test 2 var person = {    firstName    "Bill",    lastName    "Gates",     // fullName    : FirstName + "" + lastName        //Comment out this line }alert (person.firstname);           // tip "Bill"alert (person.lastname);            // tip "Gates"

The

also finds that FirstName and LastName are both correctly defined and assigned, and there is no "firstName is not defined" above.

Next I thought it was a syntax error, not explicitly specifying the attribution of the attribute, and need to use this before the attribute. Prefix:

 //  Test 3  var  person = {firstName:  "Bill" , LastName:  "Gates"  th is . FirstName + "" + this . LastName // }alert (Person.firstname);  //  Tip "Bill"  alert (                Person.lastname); //                 prompt "Gates"  alert (person.fullname); //  

The result no longer prompts the error, but FullName did not get "undefined undefined" this I unexpected value.

I thought it might be. This is not clear enough and needs to be called by person

// Test 4 var person = {    firstName    "Bill",    lastName    "Gates",    fullName     + "" + person.lastname        //  use person, error }alert (person.firstname); alert ( person.lastname); alert (person.fullname);

The result of tossing a circle back to the original point, but also an error: "Typeerror:person is undefined", the person undefined (does not exist).

......


The last number of changes and attempts I have not written clearly, I only know that I did not untie.

Knowing the recent encounter, I found that the problem can no longer make me confused. And all my thoughts were fundamentally wrong ...

Object literal attributes cannot be accessed from each other, or even errors occur. The problem is not grammatical, nor can it be resolved by changing the calling object.

Relationship to the execution environment:

To understand and solve this problem first of all need to understand the "execution environment" JS:
1, there are two types of execution environments: global (window) and local (per function), and no block-level scopes in the C language of other classes.
2, Access: The perimeter environment has access to peripheral data, and the perimeter cannot access the data in the surrounding environment
3, data attribution: Variables declared with VAR are automatically added to the nearest environment, and variables declared without VAR will default to global properties.
4, Data lookup: Data lookup and data attribution follow the "in principle", will be found in the most recent environment, can not find another layer to find, until the outermost.

Understanding these features will explain the problems of the above examples:

Test 1, because there is no "block-level scope", and data lookup will start from the nearest environment, so the JS interpreter encountered
Fullname:firstname + "" + lastName
This statement looks for the FirstName property from the window (assuming window is the closest environment), and Window.firstname does not exist. Directly using a non-existent variable to participate in the operation, of course, there will be an error

Test 3 uses this, but the creation of the person object is not completed when the This statement is implemented, and the object does not exist yet.
This time this point is the Window object, This.firstname is equivalent to Window.firstname.
In this case, test 3 seems to be the same as Test 1, but why is the result different? An error, one gets undefined.
The error handling mechanism of this interpreter is concerned, assuming there is a, b two variables, A is declared (executing var A;) and B is not.
When used, the interpreter's understanding of A is "a variable of value undefined" and can participate in the operation as long as there is a value. The Interpreter's understanding of B is an "undeclared, nonexistent variable", a variable not even undefined, and cannot participate in the operation.
For the JS interpreter, it is not the same as declaring (even if not assigning) the use of these two situations without being declared and using them directly.
An explicit call to Window.firstname is equivalent to being declared, and if it is not found, the default value is undefined, and an implicit firstName is an error if it is not found on a window and is equivalent to an undeclared call.

The person of Test 4, as stated above, does not exist at all when executing to a statement with person. The interpreter also treats this undeclared behavior as an error.


Solution Ideas:

Because there is no perfect solution to the problem in the literal sense, there is only one way to propose a solution.

First of all, for the "execution of the environment" caused by the problem, it is natural to solve it from the implementation of the environment.

Now that we know that FirstName and LastName will look up from the Window object, we'll first add it to the window so it can find it.

var firstName = "Bill",    lastName  = "Gates"; var person = {    firstName    : FirstName    lastName    : lastName    fullName    + "" + Lastname}alert (person.firstname);         // tip "Bill"alert (person.lastname);         // prompt "Gates"alert (person.fullname);         // tip "Bill Gates"

The results are correct and the person does not exist, and firstName and LastName will look from the window without causing any conflict at all.

Second, you can defer access to firstName and lastName for the "person object is not built to work" problem.

var person = {    firstName    "Bill",    lastName    "Gates",    getfullname     function () {        returnthis. lastName;    }} alert (person.getfullname);

The direct attribute is changed to a method, the object is built to be called, and this is no longer biased.

There are many other ways to avoid this problem by using new creation, or by using the literal + traditional definition method
Person.fullname = Person.firstname + "" + person.lastname;
As long as the understanding is thorough and the thinking is correct, the problem will always be solved


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.