Difference between 'var a = b' and 'th

2019-09-13 20:24发布

I have been dealing and learning about Objects and OOP in JS in the past few days and I good a basic understanding how they work now.

One thing that bothers me, and I have problems with to understand, is where is the difference between this:

var bird = "Birdy: var bird"

and this

this.bird = "Birdy: this.bird"

Both of them will add a property(bird) to the object. In this case this points to the object Window. Where is the difference? Why are people using the *this.*bird method? What are the advantages of it(could someone show me an example where this.bird is superior to var bird)?

Let´s take this tutorial for example: why is he using this there? Isnt this redundant? Couldnt this entire thing be done removing the this and/or replacing it?

1条回答
时光不老,我们不散
2楼-- · 2019-09-13 20:53

Nope youre wrong. var adds a property to the current functional context:

obj={
  add:function(){
    var plane="test";
    this.bird="test2";
  }//plane gets deleted right here as it isnt used anymoreand it was never part of obj
};

obj.add();
obj.plane;//never existed
console.log(obj.bird);
查看更多
登录 后发表回答