繁体   English   中英

Javascript 中的原型概念,我说对了吗?

[英]Prototype concept in Javascript, am I getting it right?

function Person(name, age, gender) {
    (this.name = name), (this.age = age), (this.gender = gender);
}
Person.prototype.eyecolor ="black";

var myFather = new Person("Singh", "50", "Male");
console.log(myFather.eyecolor);
console.log(myFather);
console.log(Person);

myFather inherits from Person.prototype using __proto__ which links myFather to Person.prototype ( myFather.__proto__ === Person.prototype ) and this Person constructor function inherits from Function.prototype and this Function has inherited from Object.prototype and this is why it's javascript 中的所有内容本质上都是 object。

我对这件事的理解正确吗? 我在 Prototypes in JS 中评论了我在这里所理解的内容。 在这个时间点,我不知道这个概念的实际用途。 也许当我了解更多时,我可能会看到它的一些用途。

是的,您已经正确理解了这一点。 这个概念在Javascript中称为原型链

JavaScript 对象具有指向原型 object 的链接。 当试图访问 object 的属性时,不仅会在 object 上寻找属性,还会在 object 的原型上寻找该属性,找到与原型的原型匹配的名称,依此类推,直到找到具有匹配名称的属性或结束原型链到达。

Basically this will go all the way back until it reaches the object object , which all Javascript types inherit from, whose __proto__ is null.

请注意,存在两个属性,它们基本相同: __proto__prototype 区别在于只有函数具有prototype属性,而所有对象都具有__proto__属性。 __proto__属性是非标准的,但大多数浏览器都实现了它,因此可以保存使用。

在此示例中,孩子继承父亲的姓氏:

 class Father { constructor() { this.lastName = 'Singh'; this.age = 50; this.gender = 'male'; this.eyecolor = 'black'; } } class Child extends Father { constructor(name, gender, age) { super(); this.firstName = name; this.gender = gender; this.age = age; } } const myFather = new Father(); console.log(myFather); // { lastName: 'Singh', age: 50, gender: 'male', eyecolor: 'black' } const mySelf = new Child('Saurav', 'male', 20); console.log(mySelf.firstName, mySelf.lastName); // Saurav Singh

暂无
暂无

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

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