简体   繁体   English

javascript中的示例堆栈,需要澄清“ this”的用法

[英]Example stack in javascript, need clarification on 'this' usage

I found this example and I'm unable to understand how it works: 我找到了这个示例,但我无法理解它是如何工作的:

 function Stack() { this.top = null; } Stack.prototype.push = function(val) { this.top = { data : val, next : this.top } } var S1 = new Stack(); S1.push(1); S1.push(2); console.log(S1); 

why is 'next : this.top' resolving into the previous push's 'this.top' object? 为什么'next:this.top'解析为上一个推送的'this.top'对象? and not just returning null? 不只是返回null?

When a function is called as a method of an object, its this is set to the object the method is called on. 当将函数作为对象的方法调用时,该函数将设置为调用该方法的对象。

you can see this documentation for more details 您可以查看此文档以了解更多详细信息

this in JavaScript is a game changer and it should be taken care of. this在JavaScript中是游戏规则的改变者,应予以注意。 The thing with this is that it references the context of the function you invoked. 用的东西this是它引用您调用函数的上下文。

In this case, when .push is invoked this will reference the Stack object instance. 在这种情况下,当调用.push时,它将引用Stack对象实例。

Btw console.log prints as it is being resolved, but you can't expect to have ti resolved at that point in time. Btw console.log会在解决时进行打印,但是您无法期望在那时及时解决ti。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM