过去几天我一直在处理和学习 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' 之间的区别
发布评论