-2
var myObject = {
  name: function() {
    return "Michael";
  }(),
  age: 28,
  sayName: function() {
    alert(this.name + ":" + this.age);
  }(),
  specialFunction: function() {
    myObject = this;
    if (this == myObject) altert(console.log(this.sayName));
  }
}()
};

I am trying to call the methods of an object from other methods in the same object but I'm just getting undefined.

I thought that inner scope object are allowed to access outer scope objects but this case disregards that rule.

4
  • 2
    "help me figure out what is wrong in this code" - first post the code, not some unformatted text. Commented Dec 16, 2016 at 10:24
  • 2
    Please see stackoverflow.com/help/formatting for formatting your code Commented Dec 16, 2016 at 10:28
  • Welcome to Stack Overflow! Please take the tour, have a look around, and read through the help center, in particular How do I ask a good question? and What topics can I ask about here?. From that second link: "Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it." You also must provide your question as text, not as images. Commented Dec 16, 2016 at 10:30
  • First, do not put all of your code on a single line. For one thing, breaking code into multiple lines makes it easier to narrow down the cause of an error because the error message can tell you what line causes it. Commented Dec 19, 2016 at 1:20

1 Answer 1

0

try this

(function(window){
      var myObject = {
        name: function(){
          return "Michael";
        }(),
        age: 28,
        sayName: function(){
          alert(this.name + ":" + this.age);
        },
        specialFunction : function(){
          myObject=this;
          if(this==myObject)
          alert(console.log(this.sayName));
        }
      }
      window.myObject = myObject;
    })(window);
    
    myObject.sayName();

What's happening is when you invoke the sayName function it gets its own execution environment and looks for an object named myObject which is not been defined. then it looks for this object in its container function. so what we do is define and bring this object into window object and invoke the function there. so that it can find this object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.