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();
//The values of test.count and test2.count How much are each
A question I encountered during an interview the day before yesterday. The interview question was probably when test.increase is called, what are the count values of test and test2 respectively
First, answer this The question may confuse this situation with another similar situation:
Suppose the code is changed to:
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();
//What are test3.show() and test4.show() respectively
If the question were changed to this, it would be much simpler. But the two questions don't get the same result.
========================================== Divide it
Back to the interview question, the answer to the interview question is actually 2 and 1. The reason: test.count is an attribute of test, and test2.count is actually an attribute of test2.__proto__:
When test.increase() is called, JS executes this.count ==> returns this.count; this.count = this.count 1;
this.count = this.count 1;
This seemingly simple sentence actually has an unusual meaning~~
What this sentence actually means is to create a new attribute for the instance, and this attribute is assigned the value of this.count 1.
And this.count is actually the count in the prototype chain, that is, this.count actually behaves like this when executes for the first time:
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 fun language.