久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長(zhǎng)資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      深入了解JavaScript中的構(gòu)造器

      深入了解JavaScript中的構(gòu)造器

      對(duì)構(gòu)造函數(shù)有很好的理解是你掌握J(rèn)avaScript這門(mén)語(yǔ)言的重點(diǎn)。我們都知道JavaScript不像其他語(yǔ)言,它沒(méi)有class關(guān)鍵字,但是它有跟function非常相似的構(gòu)造函數(shù)。這篇文章我們一起來(lái)詳細(xì)地了解JavaScript構(gòu)造函數(shù)如何構(gòu)造對(duì)象。

      構(gòu)造函數(shù)跟普通函數(shù)非常相似,但是我們通過(guò)new關(guān)鍵字來(lái)使用它們。主要有兩種類型的構(gòu)造函數(shù),native構(gòu)造函數(shù)(Array,Object)它們可以在執(zhí)行環(huán)境中自動(dòng)生成,還有自定義的構(gòu)造函數(shù),你可以定義自己的方法和屬性。

      當(dāng)你想要?jiǎng)?chuàng)建很多相似的對(duì)象(擁有相同的屬性和方法)的時(shí)候,使用構(gòu)造函數(shù)是非常有效的。大部分程序員都遵循公約,使用大寫(xiě)字母開(kāi)頭來(lái)將構(gòu)造函數(shù)和普通函數(shù)區(qū)分開(kāi)??纯聪旅娴拇a。

      function Book() {      // unfinished code }  var myBook = new Book();

      最后一行代碼創(chuàng)建了一個(gè)Book對(duì)象,并把它賦值給變量;這樣完成之后,即使Book構(gòu)造器沒(méi)有做任何操作,myBook也是Book實(shí)例。正如你看到的,除了首字母大寫(xiě)和使用new關(guān)鍵字之外,構(gòu)造函數(shù)和普通函數(shù)并沒(méi)有什么區(qū)別。

      判斷實(shí)例的類型

      判斷某個(gè)對(duì)象是否為某種實(shí)例,我們可以使用instanceof操作符:

      myBook instanceof Book    // => true myBook instanceof String  // => false

      注意:如果右邊不是一個(gè)函數(shù)的實(shí)例,那么將會(huì)報(bào)錯(cuò):

      myBook instanceof {}; // => TypeError: invalid 'instanceof' operand ({})

      另一種方法是使用constructor屬性,所有對(duì)象實(shí)例都有一個(gè)constructor屬性,這個(gè)屬性指向創(chuàng)建它的構(gòu)造函數(shù)。

      myBook.constructor == Book;   // => true

      就像myBook的constructor指向Book一樣。 所有對(duì)象都從它們的原型上繼承了constructor這個(gè)屬性:

      var s = new String("text"); s.constructor === String;      // => true "text".constructor === String; // => true var o = new Object(); o.constructor === Object;      // => true var o = {}; o.constructor === Object;      // => true var a = new Array(); a.constructor === Array;       // => true [].constructor === Array;      // => true

      盡管使用constructor可以用來(lái)檢測(cè)實(shí)例類型,但是建議還是使用instanceof方法。因?yàn)閏onstructor屬性是可以被重寫(xiě)的..用起來(lái)不太靠譜。

      自定義構(gòu)造函數(shù)

      構(gòu)造函數(shù)就像餅干印模。同一印模制作出來(lái)的,都是同一個(gè)diao樣(男人沒(méi)一個(gè)好東西也是這個(gè)道理)。

      function Book(name, year) {     this.name = name;     this.year = '(' + year + ')'; }

      Book構(gòu)造器需要兩個(gè)參數(shù),當(dāng)使用new關(guān)鍵字構(gòu)造對(duì)象時(shí),會(huì)把兩個(gè)形參傳給Book對(duì)象的name 和 year。

      var firstBook = new Book("Pro AngularJS", 2014); var secondBook = new Book("Secrets Of The JavaScript Ninja", 2013);  var thirdBook = new Book("JavaScript Patterns", 2010);  console.log(firstBook.name, firstBook.year);            console.log(secondBook.name, secondBook.year);            console.log(thirdBook.name, thirdBook.year);

      深入了解JavaScript中的構(gòu)造器

      如你所見(jiàn),我們可以通過(guò)傳不同參數(shù),快速創(chuàng)建另一本書(shū)。JavaScript的Array(),Date()也是這個(gè)道理。

      Object.defineProperty 方法

      Object.defineProperty 方法可以在構(gòu)造器中被使用來(lái)配置屬性。

      function Book(name) {      Object.defineProperty(this, "name", {          get: function() {              return "Book: " + name;                },                 set: function(newName) {                         name = newName;                 },                        configurable: false          });  } var myBook = new Book("Single Page Web Applications"); console.log(myBook.name);    // => Book: Single Page Web Applications // we cannot delete the name property because "configurable" is set to false delete myBook.name;     console.log(myBook.name);    // => Book: Single Page Web Applications // but we can change the value of the name property myBook.name = "Testable JavaScript"; console.log(myBook.name);    // => Book: Testable JavaScript

      上面的代碼中是調(diào)用了祖先的方法。它提供了getter和setter接口。getter方法負(fù)責(zé)返回封裝的值,setter方法接受參數(shù),并把值賦給屬性。當(dāng)我們?cè)谀硞€(gè)屬性上操作存取時(shí),調(diào)用的就是這兩個(gè)方法。通過(guò)配置configurable,我們可以設(shè)置該值能否被刪除。

      對(duì)象字面量表示法是首選的構(gòu)造函數(shù)

      JavaScript語(yǔ)言九種內(nèi)建的構(gòu)造器:Object(), Array(), String(), Number(), Boolean(), Date(), Function(), Error() 以及 RegExp()。當(dāng)我們需要?jiǎng)?chuàng)建這些值的時(shí)候,我們可以自由選擇使用字面量或者構(gòu)造器。但是相同情況下,字面量對(duì)象不僅易讀,而且運(yùn)行速度更快,因?yàn)樗麄兛梢栽诮馕龅臅r(shí)候被優(yōu)化。所以當(dāng)你需要使用簡(jiǎn)單對(duì)象的時(shí)候就使用字面量吧。

      // a number object // numbers have a toFixed() method var obj = new Object(5); obj.toFixed(2);     // => 5.00 // we can achieve the same result using literals var num = 5; num.toFixed(2);     // => 5.00 // a string object // strings have a slice() method  var obj = new String("text"); obj.slice(0,2);     // => "te" // same as above var string = "text"; string.slice(0,2);  // => "te"

      使用new關(guān)鍵字是必不可少的

      記得使用構(gòu)造器的時(shí)候要用new關(guān)鍵字,如果你不小心忘記了,那么構(gòu)造器中的this指向的是global對(duì)象(瀏覽器中默認(rèn)為window)。

      function Book(name, year) {     console.log(this);     this.name = name;     this.year = year; } var myBook = Book("js book", 2014);   console.log(myBook instanceof Book);   console.log(window.name, window.year); var myBook = new Book("js book", 2014);   console.log(myBook instanceof Book);   console.log(myBook.name, myBook.year);

      上面的代碼運(yùn)行結(jié)果如下所示:

      深入了解JavaScript中的構(gòu)造器

      如果是在嚴(yán)格模式下,上面的代碼將會(huì)拋出錯(cuò)誤,因?yàn)閲?yán)格模式不允許我們不使用new關(guān)鍵字調(diào)用構(gòu)造器。

      適用范圍更高的構(gòu)造器

      為了解決可能會(huì)忘記使用new關(guān)鍵字的風(fēng)險(xiǎn),我們可以通過(guò)判斷this的值創(chuàng)建適用范圍更高的構(gòu)造器。

      function Book(name) {      if (!(this instanceof Book)) {          // the constructor was called without "new".         return new Book(name);     }  }

      加上這段代碼之后,我們就可以‘肆無(wú)忌憚’地使用構(gòu)造器了。

      function Book(name, year) {      if (!(this instanceof Book)) {          return new Book(name, year);     }     this.name = name;     this.year = year; } var person1 = new Book("js book", 2014); var person2 = Book("js book", 2014); console.log(person1 instanceof Book);    // => true console.log(person2 instanceof Book);    // => true

      很多內(nèi)建的構(gòu)造器都是這么做的。通過(guò)判斷this是否為當(dāng)前類型。如果程序員忘記加new關(guān)鍵字,那么我們就返回一個(gè)通過(guò)new出來(lái)的對(duì)象。

      結(jié)論

      JavaScript沒(méi)有類這種說(shuō)法(但是它可以使面向?qū)ο蟮模?,所以?duì)于習(xí)慣了使用類的程序員來(lái)說(shuō)是種困惑。當(dāng)然JavaScript的構(gòu)造函數(shù)跟普通函數(shù)沒(méi)什么區(qū)別,只是通過(guò)new關(guān)鍵字生成出來(lái)而已。如果我們需要”印餅干”的話,它就非常有用了。

      贊(0)
      分享到: 更多 (0)
      ?
      網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)