-1

Consider the following simple object:

var foo = {
    constructor: function(){
        console.log("foo");
    },
    bar: function(){
        console.log("bar");
    }
}

//should return "foo\nbar"
foo.bar();

Is it possible to create a constructor for this variable object that would allow me to execute foo.bar() as well as foo.constructor() by just calling foo.bar()?

2
  • 4
    No, why would calling foo.bar() call that other function? You'd need to do this.constructor() inside of bar to achieve the desired result. It's unclear why you call this "a constructor", since it doesn't construct anything. Commented Sep 9, 2019 at 20:28
  • What is your actual problem? Commented Sep 10, 2019 at 17:37

1 Answer 1

2
var foo = {
    constructor: function(){
        console.log("foo");
    },
    bar: function(){
        this.constructor();
        console.log("bar");
    }
}

//should return "foo\nbar"
foo.bar();
Sign up to request clarification or add additional context in comments.

2 Comments

I know this is a valid answer, but in my actual JS file I have 10 or so methods, and I don't want to put this.constructor() in each method.
@evan We would need to see the rest of your code then, as there may be a better way to structure your code.

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.