1

Is in javascript possible to create php-like constructor?

I mean, in php you can do this

<?php

class myObj
{
    public function __construct()
    {
        print "Hello world!";
    }
}

//prints "Hello world!"
new myObj();

I have been playing with such an idea in JS. Is that even possible?

var myObj = function()
{
    this.prototype.constructor = function()
    {
        console.log("Hello world!");
    }
}

//I'd like to execute some actions without invoking further methods
//This should write "Hello world! into the console
new myObj();
1
  • you would put that code in the function itself, aka the constructor function. Commented Jan 3, 2014 at 22:11

3 Answers 3

3

Simple:

var myObj = function() {
    console.log("Hello world!");
}
new myObj();

There is no separate constructor, this is the constructor. The difference between myObj() and new myObj() (explanation by request (not guaranteed to be better than our custom pizzas)) is that the later will do weird stuff with this. A more complex example:

var myObj = function() {
    this.myProperty = 'whadever';
}
new myObj(); //Gets an object with myProperty set to 'whadever' and __proto__(not that you should use it, use Object.getPrototypeOf()) set to 'myObj'.

It works by substituting this for the new object. So it makes a new object ({}) and sees theNewAwesomeObject.myProperty = 'whatever'. Since there is no non-primitive return value, theNewAwesomeObject is automatically returned. If we did just myObj(), without new it wouldn't auto return, so it would have the return value of undefined.

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

2 Comments

How is new myObj() different from just doing myObj()? You should probably explain this briefly in your answer.
@dandavis I do. That was just an example of what the OP or an other user might ask.
1

My personal favorite pattern:

function Cat(){
   console.log("Cat!");
}
Cat.prototype.constructor = Cat;

Then create it like this:

var foo = new Cat();

1 Comment

thats how "The coding train" would have taught you!
0

You can have an immediately invoked function:

function MyObject() {
    var _construct = function() {
        console.log("Hello from your new object!");
    }();
}

http://jsfiddle.net/aqP9x/

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.