Every JavaScript object is associated with another object, and the associated object is what we call a "prototype". Every object inherits properties and methods from the prototype. There is a special object that does not have a prototype, which is Object. This will be explained in the following illustrations.
For example, we first declare a function Student():
function Student(name){ this.name = name; this.hello = function(){ alert(`Hello,${this.name}`); } }
This function contains an attribute name and a method hello.
In JavaScript, you can call the Student function through the new keyword (without writing new it is a normal function, writing new is a constructor), and returns an object whose prototype points to Student.prototype, as shown below:
var xiaoming = new Student("xiaoming"); alert(xiaoming.name); // xiaoming xiaoming.hello(); // Hello,xiaoming
If we want to confirm whether our assumption is correct, we will want to compare whether xiaoming.prototype and Student.prototype are equal.
But xiaoming does not have a prototype attribute, but you can use __proto__ to view it. Next, we will use these attributes to view the prototype chain between xiaoming, Student, and Object:
document.onreadystatechange = function(){ // interactive表示文档已被解析,但浏览器还在加载其中链接的资源 if(document.readyState === "interactive"){ var xiaoming = new Student("xiaoming"); alert(xiaoming.name); xiaoming.hello(); console.log("xiaoming.__proto__:"); console.log(xiaoming.__proto__); console.log("Student.prototype:"); console.log(Student.prototype); console.log("xiaoming.__proto__ === Student.prototype:" + xiaoming.__proto__ === Student.prototype); console.log("Student.prototype.constructor:" + Student.prototype.constructor); console.log("Student.prototype.prototype:" + Student.prototype.prototype); console.log("Student.prototype.__proto__:"); console.log(Student.prototype.__proto__); console.log(Object.prototype); console.log("Student.prototype.__proto__ === Object.prototype:" + Student.prototype.__proto__ === Object.prototype); } }