Code problem
function Foo() {
Foo.a = function() {
console.log(1)}this.a = function() {
console.log(2)
}
}
Foo.prototype.a = function() {
console.log(3)
}
Foo.a = function() {
console.log(4)
}
Foo.a(); / / 4
let obj = new Foo();
obj.a(); / / 2
Foo.a(); / / 1
Copy the code
Break this down in detail with some confusion:
function Foo() {
/ /...
}
let obj = new Foo()
Copy the code
New Foo() creates a new object (obj, in this case) whose internal link [[prototype]] is associated with the foo.prototype object.
Then print obj and you can see that there are currently two A methods on the object: 1. Foo internal property methods; 2. Prototype approach.
console.log(obj)
Copy the code
obj.a();
Copy the code
When calling obj.a(), the first step is to check if the object itself has this property. If it does, use it. If it does not, then use the [[Prototype]] chain of the object to find a method to call.
At this point, obj.a() finds a method that assigns this to itself, a, with an output of 2.
Foo.a();
Copy the code
At this point in code execution, Foo has already gone through the new operation, rebinding method A on global Foo, so the output is 1.
See (emphasis!!)
Articles are written in great detail and require intensive reading.
- Wood easy poplar front advanced problem 100
- Getters and setters for properties
- F.prototype
- Native prototype
- You don’t know javascript scroll up