javascript設計模式系列二-封裝

來源:互聯網
上載者:User

標籤:原型   函數   沒有   訪問   play   src   nbsp   樣本   instance   

JavaScript封裝:

var Book = function (id, name, price) {    this.id = id,        this.name = name,        this.price = price}Book.prototype.display = function () {    //展示書本}var book = new Book(10, ‘js‘, 30);book.display();console.log(book.name);

問題:通過this和prototype添加的屬性和方法有什麼區別

 答:通過this添加的屬性、方法是在當前對象上添加的,然而Js是有種基於原型prototype的語言,所以每建立一個對象時(在js中函數也是一種對象),都有一個原型prototype用於執行其繼承的屬性,方法。

 javaScript是如何?封裝的呢?

由於javascript是函數級範圍,聲明在函數內部的變數以及方法在外界是訪問不到的,通過此特性即可建立類的私人變數以及私人方法。然而在函數內部通過this船艦的屬性和方法,在類建立對象時,每個對象自身都擁有一份並且可以在外部存取到。因此通過this建立的屬性和方法可看作是對象共有屬性和對象公有方法,而通過this建立的方法,不但可以防衛這些對象的公有屬性和方法,而且還能訪問到類或對象自身的私人的屬性和方法,由於這些方法權力比較大,所以我們又將它看作特權方法。在對象建立時通過使用這些特權我們可以初始化執行個體對象的一些屬性,因此這些在建立對象時調用的特權方法還可以看作是類的構造器,如下所示:

var Book = function (id, name, price) {    //私人屬性    var num = 1;    //私人方法    function checkId() { }    //特權方法    this.setName = function (name) { }    this.getName = function () { }    //對象公有屬性    this.id = id;    this.name = name;    this.price = price;    //對象公有方法    this.copy = function () { }    //4物件建構器    this.setName(‘name‘);}

 

 類的靜態方法和屬性

//類的靜態屬性Book.isChinese=true;//類的靜態方法Book.resetTime=function(){}

 

 類的原型屬性和方法

//公有方法Book.prototype.display = function () {    //展示書本}//公有屬性Book.prototype.checkId=true;

 建立對象的安全模式:

  目的是克服初學者忘記new關鍵字,導致如下樣本,這是由於new關鍵字的作用是對當前對象的this不停的賦值,然而例子中沒有使用new,所以就會直接執行這個函數,而這個函數是在全域範圍中執行的,所以在全域範圍中this指向的是當前對象自然就是全域變數(window),而我們這個book變數最終作用是要得到Book這個類的執行結果,由於函數沒有return語句,這個Book函數自然不會告訴book變數的執行結果了,所以book為undefined

var Book = function (id, name, price) {    this.id = id;    this.name = name;    this.price = price;}var book = Book(‘12‘, ‘js‘, 30);console.log(book);//undefinedconsole.log(window.name);//‘js‘

安全模式

var Book = function (id, name, price) {    if (this instanceof Book) {        this.id = id;        this.name = name;        this.price = price;    } else {        new Book(id, name, price);    }}var book = Book(‘12‘, ‘js‘, 30);console.log(book);//Bookconsole.log(book.name);//‘js‘console.log(window.name);//undefined

 

javascript設計模式系列二-封裝

聯繫我們

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