简体   繁体   中英

php-like constructor in javascript object

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();

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 .

You can have an immediately invoked function:

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

http://jsfiddle.net/aqP9x/

My personal favorite pattern:

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

Then create it like this:

var foo = new Cat();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM