简体   繁体   English

javascript对象中的类似php的构造函数

[英]php-like constructor in javascript object

Is in javascript possible to create php-like constructor? 是否可以在javascript中创建类似php的构造函数?

I mean, in php you can do this 我的意思是,在php中您可以执行此操作

<?php

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

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

I have been playing with such an idea in JS. 我一直在用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 . 之间的差异myObj()new myObj()按要求解释(不保证比我们的定制披萨更好))是以后会做怪异的东西与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. 它通过替换this新对象。 So it makes a new object ( {} ) and sees theNewAwesomeObject.myProperty = 'whatever' . 因此,它将创建一个新对象( {} ),并看到theNewAwesomeObject.myProperty = 'whatever' Since there is no non-primitive return value, theNewAwesomeObject is automatically returned. 由于没有非原始返回值, theNewAwesomeObject将自动返回theNewAwesomeObject If we did just myObj() , without new it wouldn't auto return, so it would have the return value of undefined . 如果仅执行myObj()而不使用new ,它将不会自动返回,因此返回值将为undefined

You can have an immediately invoked function: 您可以具有立即调用的函数:

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

http://jsfiddle.net/aqP9x/ 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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