範圍安全的建構函式__函數

來源:互聯網
上載者:User

問題引入:

之前看到《js語言精粹》上,介紹js語言的糟粕,其中之一就是全域對象。當在使用建構函式時,可能忘記寫new,那對象就添加到了全域對象window上,導致了錯誤對象屬性的意外增加。

比如,一個建構函式:

function Person(gender,age){    this.gender = gender;    this.age = age;}

正確的開啟檔案應該是var p = new Person(),this指向新建立的對象。但是當忘記使用new時,如var p1 = Person(), 相當於直接調用函數,this指向全域對象。

var p = new Person('女',18);console.log(p.gender); //weiconsole.log(window.gender); //undefinedvar p1 = Person('男',23);console.log(p1.gender); //Error,p1為undefinedconsole.log(window.gender); //xiao

範圍安全的建構函式:不論是否使用new,都返回一個Person的新執行個體。

function Polygon(sides) {    if (this instanceof Polygon) {      this.sides = sides;      this.getArea = function() {        return 0;      }    } else {      return new Polygon(name);    }  }  function Rectangle(width, height) {    Polygon.call(this, 2); //借用建構函式    this.width = width;    this.height = height;    this.getArea = function() {      return this.width * this.height;    }  }  Rectangle.prototype = new Polygon(); //原型鏈繼承,實現Rectangle執行個體也是一個Polygon執行個體,從而通過Polygon建構函式中`if (this instanceof Polygon)`的校正。  var rect =  new Rectangle(5,10);  alert(rect.sides); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.