'var a = b' 之间的区别和 'this.a = b' [英] Difference between 'var a = b' and 'this.a = b'

查看:89
本文介绍了'var a = b' 之间的区别和 'this.a = b'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几天我一直在处理和学习 JS 中的对象和 OOP,我现在对它们的工作原理有了基本的了解.

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"

还有这个

this.bird = "Birdy: this.bird"

它们都会为对象添加一个属性(bird).在这种情况下,this 指向 对象 Window.区别在哪里?为什么人们使用 *this.*bird 方法?它的优点是什么(有人可以向我展示一个 示例,其中 this.bird 优于 var 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)?

让我们以这个教程为例:他为什么使用这个在那里?是多余的吗?难道这整个事情都不能删除this 和/或替换它吗?

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?

推荐答案

不,你错了.var 向当前的功能上下文添加一个属性:

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);

这篇关于'var a = b' 之间的区别和 'this.a = b'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆