javascript - js的constructor还是不太理解
怪我咯
怪我咯 2017-04-11 09:16:24
[JavaScript讨论组]
var bus = function() {
    this.maxSpeed = 100;
    this.minSpeed = 10;

    this.constructor = function (a, b) {
        this.maxSpeed = a;
        this.minSpeed = b;
    }

    this.show = function () {
        alert('maxSpeed:' + this.maxSpeed + '   this.minSpeed:' + this.minSpeed);
    }
};

var t = new bus(1000,9);
t.show();
document.writeln(t.constructor);

想重写这个方法的构造函数,结果好像没有效果。断点也没有进入constructor 方法内部。

怪我咯
怪我咯

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

全部回复(5)
天蓬老师

你new bus(), 这里的bus()就是构造函数

高洛峰

constructor 这个属性指向的是构造函数,并不是让你在 constructor 这里写一个函数

怪我咯

希望提问者可以多多看书,因为这是很基本的问题。
JS的类是很奇怪的类,差不多也是模拟的类,它并不完全,我们也不能完全用类的思想去理解它。

var t = new bus(1000,9);

该代码的执行过程是这样的:
1.系统new一个object类出来。
2.把object类传进bus函数,并绑定为它的上下文this,于是我们可以在bus函数中用this来访问它。
3.把修改后的object类赋值给变量t。

所以我们可以把bus函数看作是构造函数,因为它是在构造类时执行的。
但它执行的是bus函数,并没有执行里面的construct函数。自然跟踪不到断点执行了。

大家讲道理

怎么会没有效果了? 你已经重写成功了啊。
未重写前?

 var Bus = function() {
            this.maxSpeed = 100;
            this.minSpeed = 10;

           /*this.constructor = function (a, b) {
                this.maxSpeed = a;
                this.minSpeed = b;
           };*/

            this.show = function () {
                alert('maxSpeed:' + this.maxSpeed + '   this.minSpeed:' + this.minSpeed);
            }
        };

        var t = new Bus(1000,9);
        t.show();
        /*document.writeln(t.constructor);*/

        document.writeln(t instanceof Bus); //true
        document.writeln(t.constructor === Bus); //true

重写后

var Bus = function() {

        this.maxSpeed = 100;
        this.minSpeed = 10;

       this.constructor = function (a, b) {
            this.maxSpeed = a;
            this.minSpeed = b;
       };

        this.show = function () {
            alert('maxSpeed:' + this.maxSpeed + '   this.minSpeed:' + this.minSpeed);
        }
    };

    var t = new Bus(1000,9);
    t.show();
    /*document.writeln(t.constructor);*/

    document.writeln(t instanceof Bus); //true
    document.writeln(t.constructor === Bus); //false,这里重写成功了啊
巴扎黑

@米斯唐 解释了new一个JS对象所做的事情,你也看到了并没有哪个地方去跑constructor这个东西。
你可能在其他地方看到给constructor这个东西赋值,但可定不是期盼它在new的时候运行。它只是保留了构造函数的引用,不会被调用。除非你想手动调用:

var Bus = function() {
}

var b = new Bus();
b.constructor();

另外,我在猜测你的意图,是想提供实例化bus类时提供默认值这样的机制么?如果是的话,一般是这么写的:

var Bus = function(options) {
    this.options = {
        a: 100,
        b: 100
    };
    
    for(var p in this.options)
        if(options && options[p] !== undefined && options[p] !== null)
            this.options[p] = options[p];
}

var b1 = new Bus();         // a: 100, b: 100
var b2 = new Bus({a: 1000});// a: 1000, b: 100
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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