繁体   English   中英

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

[英]javascript - object of inherited class can access all the parent's properties and methods

我的代码是这样的:

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的构造函数Person中声明它们?

这个ia发生的原因是它使用了Person函数的Car原型。 因此,当在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的密钥,那么它就会转到proto的原型,以便找到密钥。 这种情况发生在我们找到密钥或达到null(任何原型链的末尾)之前。 如果我们达到null那么我们将得到消息,我们正在寻找的密钥是undefined ,因为它在原型链中的任何地方都找不到。 例如,让我们看看为梅赛德斯找到key 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内容将打印在控制台上。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM