简体   繁体   English

如何在对象内部调用函数

[英]How to call a function inside an object

I just started learning Javascript about a week ago and I have run in to a bit of a stumbling block. 我大约一个星期前才开始学习Javascript,但遇到了一些绊脚石。 In the link provided, I for whatever reason cannot call the function inside the object. 在提供的链接中,无论出于何种原因,我都无法调用对象内部的函数。 Any ideas what I am doing wrong? 有什么想法我做错了吗? Any advice would be great. 任何建议都很好。

Javascript code JavaScript代码

You are calling the function, but the function is returning undefined. 您正在调用该函数,但该函数返回未定义。 Be aware of the fact that this has different meanings called in different context, in testObj , this == testObj , hence this.word is undefined. 要注意的是, this有不同的含义叫不同的背景下, testObjthis == testObj ,因此this.word是不确定的。

Maybe this fiddle can help. 也许这个小提琴会有所帮助。

var testObj = {
   bar: function(){
console.log(this.word)
}
}

When you call testObj.bar Here this refers to the testObj and testObj has no property word 当您调用testObj.bar时,此处指的是testObj,而testObj没有属性字

var testObj = {
   bar: function(){
console.log(this.word)
}.bind(this)
}

Use .bind(this) or .bind(window) 使用.bind(this)或.bind(window)

Because the scope has changed. 因为范围已更改。

In JavaScript, scope refers to the current context of your code. 在JavaScript中,范围是指代码的当前上下文。 Scopes can be globally or locally defined. 范围可以是全局或本地定义的。 Understanding JavaScript scope is key to writing bulletproof code and being a better developer. 了解JavaScript范围是编写防弹代码并成为更好的开发人员的关键。 You'll understand where variables/functions are accessible, be able to change the scope of your code's context and be able to write faster and more maintainable code, as well as debug much faster. 您将了解变量/函数可在何处访问,能够更改代码上下文的范围,能够编写更快和更可维护的代码以及更快地进行调试。

So the correct code is: 因此正确的代码是:

var that = this;
var testObject = { bar: function() { return that.word }}

In your solution, "this" is "window" object. 在您的解决方案中,“ this”是“ window”对象。 So you also can code this: 因此,您还可以编写以下代码:

var testObject = { bar: function() { return window.word }}

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

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