javascript - 继承类的对象可以访问所有父类的属性和方法

时间:2017-06-27 04:40:48

标签: javascript inheritance prototype

我的代码是这样的:

function Person(firstName) {
     "use strict";
     this.firstName = firstName;
     this.fullName = "ABC";
     this.greeting = function (name) {
         console.log("Hi " + name);
     };
}

Person.prototype.hello = function () {
    "use strict";
    console.log("Hello");
};

function Car(model, year) {
    "use strict";
    this.model = model;
    this.year = year;
}

Car.prototype = new Person();
var mercedes = new Car("CS300", 2017);
mercedes.greeting("mer");
console.log(mercedes.fullName );

为什么对象 Mercedes 可以访问属性 fullName 和方法 greeting(),即使我直接在构造函数 Person.prototype 中的人?

2 个答案:

答案 0 :(得分:3)

这是因为Car的原型使用了Person函数。因此,当mercedes JavaScript引擎上找不到密钥时,会查找原型链以找到它。

您可以将mercedes.__proto__作为原型对象进行访问,以便进行验证。请查看以下代码段。



function Person(firstName) {
"use strict";
this.firstName = firstName;
this.fullName = "ABC";
this.greeting = function (name) {
    console.log("Hi " + name);
    };
}

Person.prototype.hello = function () {
    "use strict";
    console.log("Hello");
};

function Car(model, year) {
    "use strict";
    this.model = model;
    this.year = year;
}

Car.prototype = new Person();
var mercedes = new Car("CS300", 2017);

console.log(mercedes.__proto__);




一般来说,如果JavaScript引擎找不到你正在寻找对象原型的关键字,那么它就会转到proto的原型,以便找到关键字。这种情况发生在我们找到密钥或达到null(任何原型链的末尾)之前。如果我们到达null,那么我们会得到消息,我们正在寻找的密钥是undefined,因为它在原型链中的任何地方都找不到。例如,让我们查找梅赛德斯的密钥foo的值。



function Person(firstName) {
"use strict";
this.firstName = firstName;
this.fullName = "ABC";
this.greeting = function (name) {
    console.log("Hi " + name);
    };
}

Person.prototype.hello = function () {
    "use strict";
    console.log("Hello");
};

function Car(model, year) {
    "use strict";
    this.model = model;
    this.year = year;
}

Car.prototype = new Person();
var mercedes = new Car("CS300", 2017);

console.log(mercedes.foo);




正如您现在注意到的那样,undefined打印在控制台上。

这称为prototypal inheritance,它是在JavaScript中实现继承的机制。

答案 1 :(得分:0)

原型继承。 mercedes = Car = Person。如果你调用一个方法,javascript会在当前对象中搜索该方法,如果它找不到它,它就会上升到树中,直到它执行或不执行。在你的情况下,它在Person上找到它。

相关问题