js的constructor还是不太理解

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.4k
5 个回答

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

var t = new bus(1000,9);

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

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

@米斯唐 解释了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

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

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

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

 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,这里重写成功了啊
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题