求助javascript,创建一个类classA,使得 new classA === new classA()该怎么写啊?
怪我咯
怪我咯 2017-04-10 15:51:03
[JavaScript讨论组]

求助javascript,创建一个类classA,使得 new classA === new classA()该怎么写啊?

在此谢过各位了!

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
阿神

单例模式????

var ClassA = function(){

    if(ClassA.instance == null)
    {
        ClassA.instance = this;
    }
    return ClassA.instance;
}

console.log(new ClassA === new ClassA());
// 这里输出true
PHP中文网

如 @freewolf 所说,单例是一种方式。

当然,如果你只是想hack玩玩,那还有其他方式:

var A = function() {
    return A;
};

var a = new A();
var b = new A();

console.log(a === b);//true

奇怪吧?, 看new操作符的说明:

When the code new Foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from Foo.prototype.

  2. The constructor function Foo is called with the specified arguments and this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.

  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号