0

I am newly learning Javascript and vue.js. I am getting confused while accessing member variables of internal object inside an object in Vue.js as it is different from Javascript.

Assume below object in javscript,

let obj = {
    name : 'n',
    ob : {
        c : 'char',
        d : 'int'
    },
    printcd : function()
    {
        console.log(this.ob.c);
        console.log(this.ob.d);
    }
}

We are accessing 'c' and 'd' through ob (like this.ob.c). But below is the Vue.js code

ap = new Vue(
{
    el: "#app",
    data:
        {
            name:
                {
                    first: 'First',
                    last:'Last',
                    age: 30
                }
        },
    computed:
        {
            getName: function() {
                return this.name.first + ' ' + this.name.last;
            }
        }
 }

Here we are accessing first and last in getName() without using data. We are accessing this.name.first instead of this.data.name.first. Can any one please let me know why the accessing mechanism is different.

kadina
  • 5,042
  • 4
  • 42
  • 83
  • 2
    [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andreas Feb 01 '18 at 17:30
  • 1
    because the data object is exposed directly on your vue instance thus not requiring you to do go : `this.data`. Thats how vue decided to expose its data, nothing to do with it being different than `JS` because its still javaScript.. – WilomGfx Feb 01 '18 at 17:33
  • 1
    Vue.js automatically binds certain contexts to `this` whenever it instantiates components. – zero298 Feb 01 '18 at 17:33

1 Answers1

1

What you pass to new Vue is not the Vue object you get back. It is a spec to create that object. The Vue object has top-level members that are pulled from the data, methods, and computed sections of the spec. (Also the directives and components sections, I suppose, although you won't often use them directly.)

Roy J
  • 42,522
  • 10
  • 78
  • 102