最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Javascript 面試題隨筆

 更新時間:2011年03月31日 00:40:14   作者:  
前天去面試遇到的一道題,面試的問題大概是當test.increase被調(diào)用時,test和test2的count值分別是多少
復制代碼 代碼如下:

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被調(diào)用時,test和test2的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()各是多少

假如問題改成這樣,那就簡單的多了。但是兩個問題并不會得到相同的結(jié)果。
==========================================分割一下
回到面試題中,其實面試題的答案是2和1。原因呢:test.count是test的屬性,而且test2.count其實是test2.__proto__的屬性:

當test.increase()被調(diào)用時,JS執(zhí)行了this.count++ ==> 返回this.count; this.count = this.count + 1;

this.count = this.count + 1;

這句在看似簡單的語句其實有著不同尋常的意味~~

這句話的意思其實是,給實例新建一個屬性,這個屬性被賦予this.count + 1的值。

this.count 其實是在原型鏈中的count,也就是這個this.count++其實在第一次執(zhí)行的時候表現(xiàn)為:

this.count = Test.Prototype.count + 1;

可以用hasOwnProperty來驗證一下:

當var test = new Test()時。test.hasOwnProperty("count")  === false
test.increase()后。 test.hasOwnProperty("count")  === true
總的來說,JS還是一個很好玩的語言。

相關(guān)文章

最新評論

金湖县| 浦北县| 涞源县| 内江市| 伊吾县| 偏关县| 石景山区| 伊川县| 东安县| 靖边县| 麻江县| 河东区| 新巴尔虎左旗| 德保县| 利川市| 淄博市| 利辛县| 沁水县| 玉山县| 沂南县| 广安市| 广南县| 罗甸县| 洛扎县| 象州县| 耒阳市| 弋阳县| 长乐市| 咸宁市| 仙居县| 赣榆县| 冀州市| 山丹县| 定安县| 海盐县| 深泽县| 庆城县| 大冶市| 建瓯市| 江阴市| 维西|