原型对象Javascript

时间:2015-10-22 11:10:32

标签: javascript object prototype

当我创建一个原型对象,并将它用于一个新实例时,我应该期望该对象的名称与我调用它的方式相同。我的原型名为AUTO,新的原型名为BMW

var auto = function(a,b,c) {

    this.a = a;
    this.b = b;
    this.c = c;

};

var bmw = new auto("blue", true, 123);

console.log(bmw);

所以这个的结果是: auto {a:" blue",b:true,c:123}

但我期待 宝马{a:"蓝",b:是,c:123}

然而,当我触发这段代码时,console.log(bmw.a);我收到了正确的价值。

所以我的问题是:为什么BMW = auto {a:" blue",b:true,c:123}而不是BMW {a:" blue",b :true,c:123}

1 个答案:

答案 0 :(得分:0)

您的宝马是原型auto实例。它的名称BMW只是存储此实例的变量。试试这个例子:

var auto = function(a,b,c) {
    this.a = a;
    this.b = b;
    this.c = c;
};

var bmw = new auto("blue", true, 123);

document.write('<br />What is BMWs type? ');
document.write(typeof bmw);
document.write('<br />What is autos type? ');
document.write(typeof auto);
document.write('Is BMW an instance of auto? ');
document.write(bmw instanceof auto ? 'Yes' : 'No');

简而言之,bmw是保存原型Auto实例的变量 - 不是新原型。 Auto是构造函数 - 它的类型是Function。原型(或不同语言的类)只是默认情况下定义某个对象的结构和方法的通用对象。例如,您可以制作“车辆”的原型,然后从这两个原型中获得两个车辆和四轮车。然后你可以制造一辆新的四轮车,但这次你要制造一辆实际的车辆,给它一个名字等等......

如果您想为宝马制作一个特定的原型,您应该使用正确的方法继承它:

var bmw = function(a,b,c) {
    // Using `call` will run the constructor of auto, with the context of `this`
    auto.call(this, a, b, c);
    // Then we can do prototype specific things here
    this.brand = 'BMW';
};
var bmw = new bmw("blue", true, 123);

添加原型方法后,您还必须使用Object.create(auto.prototype)将其正确链接。

查看MDN以获取更多信息 - 请在那里阅读:https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain