久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放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. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

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

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

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

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

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

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

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

      判斷實例的類型

      判斷某個對象是否為某種實例,我們可以使用instanceof操作符:

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

      注意:如果右邊不是一個函數(shù)的實例,那么將會報錯:

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

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

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

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

      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可以用來檢測實例類型,但是建議還是使用instanceof方法。因為constructor屬性是可以被重寫的..用起來不太靠譜。

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

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

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

      Book構(gòu)造器需要兩個參數(shù),當使用new關(guān)鍵字構(gòu)造對象時,會把兩個形參傳給Book對象的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)造器

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

      Object.defineProperty 方法

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

      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方法負責返回封裝的值,setter方法接受參數(shù),并把值賦給屬性。當我們在某個屬性上操作存取時,調(diào)用的就是這兩個方法。通過配置configurable,我們可以設(shè)置該值能否被刪除。

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

      JavaScript語言九種內(nèi)建的構(gòu)造器:Object(), Array(), String(), Number(), Boolean(), Date(), Function(), Error() 以及 RegExp()。當我們需要創(chuàng)建這些值的時候,我們可以自由選擇使用字面量或者構(gòu)造器。但是相同情況下,字面量對象不僅易讀,而且運行速度更快,因為他們可以在解析的時候被優(yōu)化。所以當你需要使用簡單對象的時候就使用字面量吧。

      // 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)造器的時候要用new關(guān)鍵字,如果你不小心忘記了,那么構(gòu)造器中的this指向的是global對象(瀏覽器中默認為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);

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

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

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

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

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

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

      加上這段代碼之后,我們就可以‘肆無忌憚’地使用構(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)造器都是這么做的。通過判斷this是否為當前類型。如果程序員忘記加new關(guān)鍵字,那么我們就返回一個通過new出來的對象。

      結(jié)論

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

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