'var a = b' 和 'this.a = b' 之间的区别

编程入门 行业动态 更新时间:2024-10-10 14:29:21
本文介绍了'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' 之间的区别

本文发布于:2023-11-25 21:47:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   var

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!