欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

簡單分析javascript面向對象與原型

 更新時間:2015年05月21日 10:05:00   投稿:hebedich  
為了說明 JavaScript 是一門徹底的面向對象的語言,首先有必要從面向對象的概念著手 , 探討一下面向對象中的幾個概念:1.一切事物皆對象,2.對象具有封裝和繼承特性,3.對象與對象之間使用消息通信,各自存在信息隱藏

本文主要內容參考來自JavaScript高級程序設計,面向對象與原型章節(jié):

1、工廠模式

ECMAScript 可以通過工廠模式來創(chuàng)建對象:

//工廠模式
function createObject(name, age) {
  var obj = new Object();                  //創(chuàng)建對象
  obj.name = name;                      //添加屬性
  obj.age = age;
  obj.run = function () {                    //添加方法
    return this.name + this.age + '運行中...';
  };
  return obj;                            //返回對象引用
};
var obj1 = createObject('Lee', 100);          //創(chuàng)建第一個對象
var obj2 = createObject('Jack', 200);          //創(chuàng)建第二個對象
//alert(obj1.run());                          //打印第一個對象實例的run()方法
//alert(obj2.run());                          //打印第二個對象實例的run()方法

//alert(typeof obj1);
//alert(typeof obj2);
alert(obj1 instanceof Object); //true
alert(obj2 instanceof Object); //true

通過工廠模式創(chuàng)建的對象,解決了重復實例化問題,但對象識別問題無法解決(所有對象均是Object),因此要想解決對象識別問題,我們采用下面的構造函數(shù)。

2、構造函數(shù)

//構造函數(shù)創(chuàng)建
function Person(name,age){  //所有構造函數(shù)對象都是Object
  this.name=name;
  this.age=age;
  this.run=function(){
    return this.name+this.age+"ing...";
  };
};
var person1=new Person('zhu1',100);
var person2=new Person('zhu2',200);
alert(person1.run());
alert(person2.run());

alert(person1 instanceof Object); //ture
alert(typeof person2);         //Person
alert(person2 instanceof Person);  // true
var person3=new Object();
Person.call(person3,'zhu3',300);//對象冒充,person3是Object類型,冒充Person類型
alert(person3.run()); 

構造函數(shù)中this:代表當前作用域對象的引用,如果在全局范圍this代表window對象,如果在構造函數(shù)體內,就代表當前構造函數(shù)所聲明的對象。

構造函數(shù)方法,及解決了重復實例化問題,有解決了對象識別問題,對比跟工廠方法不同之處可知:

1.構造函數(shù)方法沒有顯示的創(chuàng)建對象(new Object());

2.直接將屬性和方法值賦值給this;

3.沒有return 語句;

4.但是使用構造函數(shù)創(chuàng)建必須使用new運算符;

以上所述就是本文的全部內容了,希望大家能夠喜歡。

相關文章

最新評論