I encountered a question during the interview the day before yesterday. The interview question is probably what the count values of test and test2 are when test. increase is called.
The Code is as follows:
Var Fundamental = {count: 1 };
Function Test (){}
Test. prototype = Fundamental;
Test. prototype. increase = function () {this. count ++ ;};
Var test = new Test ();
Console. log (test. count );
Var test2 = new Test ();
Console. log (test2.count );
Test. increase ();
// What are the values of test. count and test2.count?
I encountered a question during the interview the day before yesterday. The interview question is probably what the count values of test and test2 are when test. increase is called.
First, the answer to this question may confuse this situation with another similar situation:
If you change the code:
The Code is as follows:
Function FundamentalModified (){
Var count = 1;
This. increase = function (){
Count ++;
}
This. show = function (){
Return count;
}
}
Function TestModified (){}
TestModified. prototype = new FundamentalModified ();
Var test3 = new TestModified ();
Var test4 = new TestModified ();
Test3.increase ();
// Test3.show () and test4.show ()
If the problem is changed to this, it would be much simpler. But the two questions won't get the same result.
========================================================== = Split
Return to the interview question. In fact, the answer to the interview question is 2 and 1. Why: test. count is the property of test, and test2.count is actually the property of test2. _ proto:
When test. increase () is called, JS executes this. count ++ => to return this. count; this. count = this. count + 1;
This. count=This. count+ 1;
This seemingly simple statement actually has an unusual meaning ~~
In fact, a new attribute is assigned to an instance.This. count+ 1 value.
WhileThis. countIn fact, it is the count in the prototype chain, that is, this. count ++ is actually inFirst executionWhen the performance is:
This. count = Test. Prototype. count + 1;
You can use hasOwnProperty to verify it:
When var test = new Test. Test. hasOwnProperty ("count") = false
After test. increase. Test. hasOwnProperty ("count") = true
In general, JS is still a very interesting language.