0

Trying to use composition over inheritance with factory functions in Javscript and I am getting function is not defined with the following code:

(dogIsCreated is not defined)

var dog = function dog(state) {
  return {
    create: function create() {
      console.log('Create the dog');
      dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('Ready');
    }
  }
}

var ted = dog().create();

Be amazing if someone could point me in the right direction? Am I using completely the wrong syntax.

Thanks :)

5
  • right there var dog = function dog(state). Commented Jan 14, 2016 at 16:05
  • 1
    There is no function with name dogIsCreated (at least in the scope you are trying to call it from). dogIsCreated is a property on the object. Maybe you meant this.dogIsCreated() ? Commented Jan 14, 2016 at 16:06
  • 1
    @Tresdin: There is no issue in that line. Commented Jan 14, 2016 at 16:06
  • could we have an explaination why this is required? Commented Jan 14, 2016 at 16:09
  • this.dogIsReady() - what an imbecile I am! Thank you :) Commented Jan 14, 2016 at 16:09

2 Answers 2

1

You need to define the scope the create() method is apart of using the this keyword.

var dog = function dog(state) {
  return {
    create: function create() {
      console.log('Create the dog');
      this.dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('Ready');
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The explanation reads a bit strange. It sounds like we have to change the visibility of create (which we don't).
1

This (dogIsCreated)is not a global function. dogIsCreated function created with dog Object. this is object method , so you are calling this method inside another (same)object method, so we can call that method using 'this'–

var dog = function dog(state) {
  return {
    create: function create() {
      console.log('Create the dog');
      this.dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('Ready');
    }
  }
}

var ted = dog().create();

3 Comments

Code without explanation is rarely helpful. No one likes to play the "spot the difference" game.
This (dogIsCreated)is not a global function. dogIsCreated function created with dog Object. this is object method
Basically yes. You can edit your answer to provide more information.

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.