实例创建

时间:2013-01-29 09:07:34

标签: javascript

var Vehicle = function Vehicle() {
 // ...
}

var vehicle = new Vehicle();

当调用新的Vehicle()时,JavaScript会做四件事:

  1. 它会创建一个新对象。
  2. 它将对象的构造函数属性设置为Vehicle。
  3. 设置委托给Vehicle.prototype的对象。
  4. 它在新对象的上下文中调用Vehicle()。
  5. 第三点是什么?这是否意味着新对象构造函数原型设置为function.prototype?代表在这里意味着什么?

3 个答案:

答案 0 :(得分:2)

这意味着:

vehicle.constructor.prototype === Vehicle.prototype; // true

因此,Vehicle.prototype对象可以使用vehicle上可用的方法。

答案 1 :(得分:1)

您只需将委托视为参考,每个对象都有[[Prototype]]内部属性,并引用其构造函数的原型 ,所以:

Object.getPrototypeOf(vehicle) === Vehicle.prototype; // always true

这是关于new运营商正在做什么的seudo代码:

function fakeNew(constructor) {
    var instance = {};
    instance.__proto__ = constructor.prototype;
    instance.constructor = constructor;
    constructor.apply(instance, [].slice.call(arguments, 1));
    return instance;
}

答案 2 :(得分:0)

var Vehicle = function Vehicle() {
    this.engine = {running:false};
}
Vehicle.prototype.startEngine = function () {
    this.engine.running = true;
};

var vehicle1 = new Vehicle();
vehicle.startEngine();
// vehicle.engine.running === true
var vehicle2 = new Vehicle();
vehicle2.startEngine = function () {
    throw "err";
};
vehicle2.startEngine();
// Error: "err"

Javascript是基于原型的,因此每个对象都继承自另一个对象(原型)。 当您在对象上调用属性时,它首先在自己的范围内搜索该属性,如果找不到该属性,则在属性链中上升。

相关问题