欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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)文章

  • js String.prototype.trim字符去前后空格的擴展

    js String.prototype.trim字符去前后空格的擴展

    這篇文章主要介紹了js String.prototype.trim字符去前后空格的擴展,需要的朋友可以參考下
    2020-04-04
  • 最新評論