Reputation: 2306
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();
Upvotes: 1
Views: 527
Reputation: 11498
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
.
Upvotes: 3
Reputation: 1392
My personal favorite pattern:
function Cat(){
console.log("Cat!");
}
Cat.prototype.constructor = Cat;
Then create it like this:
var foo = new Cat();
Upvotes: 1
Reputation: 104785
You can have an immediately invoked function:
function MyObject() {
var _construct = function() {
console.log("Hello from your new object!");
}();
}
Upvotes: 0