Javascript面接試験問題エッセイ

1746 ワード

 
  
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();
//test.count test2.count
一昨日面接に行きましたが、面接の問題はtest.increaseが呼び出された時、testとtest 2のcount値はそれぞれいくらですか?
まず、この問題に答えると、このような状況を他の類似の状況と混同する可能性があります.
コードを変更したら:
 
  
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() test4.show()
問題がこのようになったら、もっと簡単になります.しかし、二つの問題は同じ結果を得られません.
===============================================================================================
面接の問題に戻りますが、実は面接の答えは2と1です.その理由はtest.co untはtestの属性で、test.2 countはtest 2.uプロト.の属性:
test.increase()が呼び出されると、JSはthis.com unt+=>を実行してthis.com untに戻る.this.com unt=this.com unt+1;
this.com unt=this.com unt+1;
この文は簡単に見える言葉には普通ではない意味があります.
この文の意味は、インスタンスに属性を新規作成し、この属性はthis.com unt+1の値を与えられるということです.
this.com untは実はプロトタイプのチェーンの中のcountで、つまりこのthis.com unt+は実は初めて実行する時に表しています.
this.com unt=Test.Prottype.com unt+1;
ハスOwnPropertyで検証できます.
var test=new Test()の場合.test.hasOwnProperty(「count」)  === falsetest.increase()の後.test.hasOwnProperty(「count」)  === trueは総じてJSの面白い言葉です.