在函数内调用对象的方法

时间:2022-04-10 21:33:48

I know how to call a method from an object i.e. the following if myObj.objMethod is called it will return string.

我知道如何从一个对象调用一个方法,即如果myObj.objMethod被调用,它将返回字符串。

myObj = {
  objProperty: 'string',
  objMethod: function() {
    return this.objProperty
  }
}

However, I am attempting the following code wars exercise and cannot figure out what needs to be done. It looks like they want the function to be called within itself. To do this i have tried using arguments.callee.call(MyObject.objMethod()) but, as expected this exceeds the max call stack. Has anyone got any idea if this is possible to call a method of an object of a function, from within that function?

但是,我正在尝试以下代码大战练习,无法弄清楚需要做什么。看起来他们希望在自身内部调用函数。为此,我尝试使用arguments.callee.call(MyObject.objMethod())但是,正如预期的那样,这超出了最大调用堆栈。有没有人知道是否可以从该函数中调用函数对象的方法?

Here is (one of) my attempt(s) below:

这是(我的)以下尝试之一:

function myFunction() {

  var MyObject = {
    objProperty: "string",
    objMethod: function() {
      return this.objProperty;
    }
  }

  return arguments.callee.call(MyObject.objMethod());

};

Here are the code wars instructions:

以下是代码大战说明:

Property objMethod should be called by myFunction.

属性objMethod应该由myFunction调用。

Can you fix the syntax so myFunction will be working again? Please check things like braces, commas, and letter case.

你能修复语法,以便myFunction再次运行吗?请检查大括号,逗号和字母大小写。

and here is the original code provided:

这是提供的原始代码:

function myFunction() {
  var MyObject = {
    objProperty: "string",
    objMethod: function() {
      return myObject.objProperty;
        }
  }

  return myObject.Objmethod();
};

2 个解决方案

#1


2  

This is your solution

这是你的解决方案

function myFunction() {
  var MyObject = {
    objProperty: "string",
    objMethod: function() {
      return MyObject.objProperty;
    }
  }

  return MyObject;
};

The problem statement is

问题陈述是

Property objMethod should be called by myFunction.

属性objMethod应该由myFunction调用。

It passes all the tests.

它通过了所有测试。

#2


0  

Make sure you look at the test and what it is expecting. The test is expecting to be able to reference the object, not one particular property.

确保你看看测试及其期望。期望测试能够引用对象,而不是一个特定属性。

return MyObject;

#1


2  

This is your solution

这是你的解决方案

function myFunction() {
  var MyObject = {
    objProperty: "string",
    objMethod: function() {
      return MyObject.objProperty;
    }
  }

  return MyObject;
};

The problem statement is

问题陈述是

Property objMethod should be called by myFunction.

属性objMethod应该由myFunction调用。

It passes all the tests.

它通过了所有测试。

#2


0  

Make sure you look at the test and what it is expecting. The test is expecting to be able to reference the object, not one particular property.

确保你看看测试及其期望。期望测试能够引用对象,而不是一个特定属性。

return MyObject;