简体   繁体   English

如何在对象中调用方法

[英]How to call a method in an object

I am having trouble calling the object method,it always throw a error this.b is not a function 我在调用对象方法时遇到麻烦,它总是抛出错误this.b不是函数

var a={
   b:()=>"3333",
   c:()=>this.b();
}
console.log(a.c());

Simplest way to make your code working is to use a instead of this 使代码正常工作的最简单方法是使用a代替this

var a = {
   b: () => "3333",
   c: () => a.b()
};

console.log(a.c());

Your code does not work because the arrow function binds the function to the scope in which it is defined. 您的代码无法正常工作,因为arrow函数将函数绑定到了定义它的作用域。 In this case, you are in the global scope when you create the function "c" using the arrow function. 在这种情况下,使用箭头函数创建函数“ c”时,您位于全局范围内。 Often this can be fixed with a bind call. 通常,可以通过绑定调用解决此问题。 However, in this case, I would just convert to a classical function. 但是,在这种情况下,我将转换为经典函数。 This is a good lesson in why you should not be lazy and use the arrow function to save a few characters. 这是一个很好的课程,说明了为什么您不应该懒惰,并使用箭头功能保存一些字符。 The arrow function IS NOT the same as a normal function and can lead to hard to debug bugs. 箭头功能与普通功能不同,它可能导致难以调试的错误。

 var a={ b:()=>"3333", c:function () { return this.b() } } console.log(ac()) 

Basically, the reference of c, will call the value based on lexical scope, the same of ' window.c() '. 基本上,c的引用将基于词法范围调用值,与' window.c() '相同。

To fix your implementation, do: 要修复您的实现,请执行以下操作:

var a={
   b:()=>{ return "333"; },
   c:function(){ return this.b(); }
}
console.log(a.c()); // Here we have a "333"

Why this happens? 为什么会这样?

The function expressions work about dynamic scope, different of Arrow Functions. 函数表达式在动态范围方面起作用,这与箭头函数不同。 To access Object Properties and reference to same this, use { yourProperty: function() { return "Hello, World"; } } 要访问对象属性并对此进行引用,请使用{ yourProperty: function() { return "Hello, World"; } } { yourProperty: function() { return "Hello, World"; } }

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

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