![Image for post](https://miro.medium.com/max/9999/1*Ajt4AQgGP21RRt4nwQXi_g.png)
JavaScript原型 (JavaScript Prototype)
Prototypes are the mechanism by which JavaScript objects inherit features from one another. Prototypes can be used to add properties and methods into existing constructor.
原型是一种机制,JavaScript对象通过该机制彼此继承特征。 原型可用于将属性和方法添加到现有构造函数中。
Lets say, We have one constructor function:
可以说,我们有一个构造函数:
function Person(name) {this.name = name;}
Now, I am creating a instance to access members of this constructor
现在,我正在创建一个实例来访问此构造函数的成员
let obj = new Person(‘Premal’);
Now, you can access properties like this:
现在,您可以访问如下属性:
console.log(‘Name ’, obj.name);
Till this example everything was okay but what if I want to add one property into an existing constructor?
直到这个示例一切正常,但是如果我想向现有构造函数添加一个属性怎么办?
You can’t add it directly like this.
您不能像这样直接添加它。
Person.gender = ‘Male’;
It will give you undefined when you try to access it.
当您尝试访问它时,它将给您未定义的信息。
Instead, use a prototype to add properties and methods in the constructor.
而是使用原型在构造函数中添加属性和方法。
Person.prototype.gender = 'male'
JavaScript原型链 (JavaScript Prototype Chaining)
type Object.prototype in console and see what happens
在控制台中输入Object.prototype,看看会发生什么
![Image for post](https://miro.medium.com/freeze/max/9999/1*-rLWxfOtKunHLLJRBTSkZw.gif)
You can see in the above image that a large number of methods are defined in Object’s prototype property. This is called prototype chaining. These properties will be available in objects that inherit from Object.
您可以在上图中看到在Object的prototype属性中定义了许多方法。 这称为原型链。 这些属性在从Object继承的对象中可用。
Let’s learn from example:
让我们从示例中学习:
let obj = {};
I have defined one object above that inherits from Object.
我在上面定义了一个继承自Object的对象。
Now, try to call this variable named obj
现在,尝试调用名为obj的变量
Write obj. In console
写obj。 在控制台中
![Image for post](https://miro.medium.com/freeze/max/9999/1*EkEXUDXgfJrFF5xtUJdYEQ.gif)
Code will show all the predefined methods of Object that we have seen earlier.
代码将显示我们之前看到的Object的所有预定义方法。
As we know all JavaScript objects inherit properties and methods from prototype. We can see another example of prototype chaining.
众所周知,所有JavaScript对象都从原型继承属性和方法。 我们可以看到原型链接的另一个示例。
lets define one string variable in console:
让我们在控制台中定义一个字符串变量:
let a = ‘premal’
type a. and see all the methods and properties of string called JavaScript prototype chaining
输入a。 并查看称为JavaScript原型链的字符串的所有方法和属性
![Image for post](https://miro.medium.com/freeze/max/9999/1*3AeVEsjoLDsZ1yltmqCDdg.gif)
You can see all string methods and properties that is what prototype chaining is.
您可以看到原型链接就是所有的字符串方法和属性。
Source of Blog: http://www.premalkatigar.com/technology/understanding-javascript-prototype-and-prototype-chaining/
博客来源: http : //www.premalkatigar.com/technology/understanding-javascript-prototype-and-prototype-chaining/
Happy coding!
编码愉快!
翻译自: https://medium.com/@premal.katigar/understanding-javascript-prototype-and-prototype-chaining-1378cbe32aa7