js容易被忽視的問題

來源:互聯網
上載者:User

標籤:style   blog   class   code   c   java   

一、範圍和全域變數

var test=function(){    var a=1;    setTimeout(function(){        console.log(a);        a=2;    },1000);    a=3;    setTimeout(function(){        console.log(a);        a=4;    },2000); };test();

結果是3,2;

共用記憶體。setTimeout等非同步,是取現在當時的a的值。執行第一個setTimeout的時候,a=3,已經執行了。

 二、全域變數和new變成全域的

var foo=10;var a=1;var  main = function (){//a=10;console.log(a);a=20;console.log(this.foo);this.foo=foo;console.log(this.foo);foo=1000;console.log("111111111111");}var s=main();var d=new main();

1

10

10

111111111111

 

20

undefined

1000

111111111111

不加new 都是全域的,this指向的全域變數。所以第一個就取得是全域的值。

 

第二個加new 了,this.foo指向的是自己,沒有定義於是就報undefined。外面a foo等是全域變數,main(),執行後,a已經變成20了,foo也變成1000了,所以值發生變化了,因為全域變數。

var foo=10;var a=1;var  main = function (){//a=10;console.log(a);a=20;console.log(this.foo);this.foo=foo;console.log(this.foo);foo=1000;console.log("111111111111");}//var s=main();var d=new main();

如果不執行第一個,結果發生變化。可以發現其實是全域變數的修改。

1 

undefined

10

111111111111

三、快速的判斷Array類型

 var toString = Object.prototype.toString;  var isArray = Array.isArray || function(val) {    return toString.call(val) === ‘[object Array]‘;  };  function isString(val) {    return toString.call(val) === ‘[object String]‘;  }  function isFunction(val) {    return toString.call(val) === ‘[object Function]‘;  }

四、attribute和Property的區別

 

attribute

input節點有很多屬性(attribute):‘type’,‘id‘,‘value‘,‘class‘以及自訂屬性,在DOM中有setAttribute()和getAttribute()讀寫DOM樹節點的屬性(attribute)

PS:在這裡的getAttribute方法有一個潛規則,部分屬性(input的value和checked)通過getAttribut取到的是初始值,這個就很好的解釋了之前的n1為1。

Property

javascript擷取到的DOM節點對象,比如a 你可以將他看作為一個基本的js對象,這個對象包括很多屬性(property),比如“value”,“className”以及一些方法,setAttribute,getAttribute,onclick等,值得注意的是對象的value的屬性(property)取值是跟著輸入框內的當前值一起更新的,這解釋了之前的n2為什麼為1000了。

 

五、關於hasOwnPropery

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.