javascript原型模式用法執行個體詳解

來源:互聯網
上載者:User

javascript原型模式用法執行個體詳解

   本文執行個體講述了javascript原型模式用法。分享給大家供大家參考。具體分析如下:

  一般在瞭解了原廠模式和建構函式模式的弊端之後,就知道為什麼需要原型模式了

  原型模式i的定義:每個函數都有一個prototype(原型)屬性,這個屬性是一個對象,它的用途是包含可以由特定類型的所有執行個體共用的屬性和方法。比如在建構函式模型中sayInformation()方法,如果聲明兩個執行個體就要構造兩次sayInformation方法,但是聲明兩次是沒有必要的,這就是為什麼有原型模式的出現(尼瑪,網上那些部落格上面都是扯談的東西,還是看書講的容易理解),sayInformation()聲明為原型模式之後,執行個體就共用了,就沒有必要聲明兩次了

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

function Person(){}

Person.prototype.name="jack";

Person.prototype.age=10;

Person.prototype.sayInformation=function()

{

console.log("my name is"+this.name+" age is"+this.age);

}

var person1 = new Person();

person1.sayInformation();

console.info(person1.name);

//來自原型的屬性name

person1.name="Greg";

//修改執行個體的name屬性

console.info(person1.name);

//來自執行個體的屬性name

delete person1.name ;

//來自執行個體的屬性,這裡刪除的是執行個體的屬性,但是原型的屬性依然存在

console.info(person1.name);

//來自原型的屬性name

var person2 = new Person();

person2.sayInformation();

console.info(person1.hasOwnProperty("name"));

//hasOwnProperty檢查屬性是屬於執行個體還是原型中,如果是執行個體中就返回true

console.info(person1.name==person2.name);

console.info(person1.sayInformation==person2.sayInformation);

console.info(person1.constructor);

//指向person1的建構函式

//原型更加簡便的寫法

function Person2(){}

Person2.prototype={

name:"jack",

age:29,

sayInformationfunction:function()

{

console.log("my name is"+this.name+" age is"+this.age);

}

}

  希望本文所述對大家的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.