search

Home  >  Q&A  >  body text

javascript - Why can't this.xxx be used to declare attributes in the method of creating an object with var obj = {}?

Whyvar obj = {}Cannot use this.xxx to declare attributes in the method of creating an object?

like:

var  person = {
   this.name = '背锅侠';
}

will report an error. After looking at its constructor, it is also Object. Why would this happen? In addition, I would like to ask what is the difference between .json and an object?

仅有的幸福仅有的幸福2705 days ago1041

reply all(3)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-07-05 10:53:33

    This points to an uncertain future caller, which is related to the scope. Whoever calls the function, this inside the function points to whom.

    function Person (name) {
        this._name = name;
    }
    var p1 = new Person('sarah');
    var p2 = new Person('tom');

    The above uses the new keyword to call the Person() function, and passes in a string 'sarah' as ​​the value of name. At this time, the point of this inside the function is p1. In the same way, the other one points to p2. If the Person('sarah') method is called directly, since the scope of Person() is the global scope, then the internal this will point to the window.

    In other words, this is a substitute, pointing to objects that may be involved in the future. It is uncertain. The internally defined attribute points will also change accordingly.

    But like the object literal form used by the subject, the pointing of the attribute name is certain, it belongs to the person. The person object defined by the subject is equal to my p1 here.

    In addition, as mentioned above, json is a data format. Facilitates data transfer between front and backends.

    I don’t know if I made it clear. . . Newbie answers.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 10:53:33

    Isn’t this how object literals create objects?
    The part on the right is obviously in JSON format and only accepts Key-Value form

    The difference between JSON and objects
    Give me an example

    var obj ={ "you" : "a good boy" }
    The part on the right is the JSON you mentioned
    It is the same whether it is written in .json or .js
    In fact, it is a data format that looks like this sub

    As for objects, everything is an object. Object is a relatively abstract term

    The constructors are all .json? Yes, they are all the same data format

    reply
    0
  • 世界只因有你

    世界只因有你2017-07-05 10:53:33

    The first question you have to askBrendan Eich.
    Ask him why JavaScript was designed like this in the first place.

    As for the second question, JSON is a data format , and objects... let’s assume you are talking about JavaScript. Objects are a data type of JavaScript.

    reply
    0
  • Cancelreply