This is the first day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Prototype chain
Important Points
- All objects are passed
The new function
create - All functions are also objects
new Function()
- Functions can have properties
Array.from
- All objects are reference types
Definition:
A prototype is a property of a function object that defines the common ancestor of the object created by the constructor. Objects generated by this constructor can inherit the properties and methods of the stereotype. Prototypes are objects.
Prototype prototype
All functions have one property: prototype, called the function prototype
By default, Prototype is a normal Object
By default, prototype has a property, constructor, which is also an object that points to the constructor itself.
Implicit prototype proto
All objects have one property: proto, called an implicit stereotype
By default, an implicit stereotype points to the stereotype of the function that created the object.
When accessing members of an object:
- See if the object itself owns the member, and if it does use it directly
- Look in the prototype chain to see if you have the member, and if you have it directly
Monkey patch: Adds members to a function prototype to enhance the functionality of the object. monkey patch can contaminate the prototype, use with caution.
Prototype chain
Just focus on this diagram:
Special point:
- Function’s proto points to its prototype
- Object’s Prototype proto points to null
Here are some common interview questions
1.
var F = function () {}
Object.prototype.a = function () {}
Function.prototype.b = function () {}
var f = new F();
console.log(f.a, f.b, F.a, F.b);
// fn undefined fn fn
2.
function A() {}
function B(a) {
this.a = a;
}
function C(a) {
if (a) {
this.a = a;
}
}
A.prototype.a = 1;
B.prototype.a = 1;
C.prototype.a = 1;
console.log(new A().a); / / 1
console.log(new B().a); //undefined
console.log(new C(2).a); / / 2
3. function User() {}
User.prototype.sayHello = function() {}
var u1 = new User();
var u2 = new User();
console.log(u1.sayHello === u2.sayHello); //true
console.log(User.prototype.constructor); //User Function
console.log(User.prototype === Function.prototype); // false
console.log(User.__proto__ === Function.prototype); // true
console.log(User.__proto__ === Function.__proto__); // true
console.log(u1.__proto__ === u2.__proto__); // true
console.log(u1.__proto__ === User.__proto__); // false
console.log(Function.__proto__ === Object.__proto__); // true
console.log(Function.prototype.__proto__ === Object.prototype.__proto__); // false
console.log(Function.prototype.__proto__ === Object.prototype); // true
Copy the code