1. 程式人生 > >第5天:自定義建構函式,建立物件(簡單工廠模式)

第5天:自定義建構函式,建立物件(簡單工廠模式)

面向物件

封裝、繼承、多型(抽象性)

js是一門基於物件的語言

萬物皆物件

物件:有屬性和方法,具體特指的某個事物

物件:有特徵和行為,具體特指的某一事物

javaScript 中的所有事物都是物件:字串、數值、陣列、函式...
此外,JavaScript 允許自定義物件。

如何獲取該變數(物件)是不是屬性什麼型別的?
語法:
變數 instanceof 型別的名字——————>布林型別,true就是這種型別,false不是這種型別
在當前的物件方法中,可以使用this關鍵字代表當前的物件

    //人的物件
    var person = new Object();
    person.name = "小萌";
    person.age = 10;
    person.sayHi=function(){

    //在當前這個物件的方法中是可以訪問當前這個物件的屬性的值
    //在當前物件方法用可以使用this關鍵字代表當前物件
    console.log("我叫"+this.name+",今年"+person.age+"了");
    }
    person.sayHi();

如何一次性建立多個物件?
把建立物件的程式碼封裝到一個函式中

簡單工廠建立物件

function createObject(name,age){
        var person = new Object();//建立物件
        person.name = name;//為物件新增屬性
        person.age = age;
        person.sayHi=function(){//為物件新增方法
            console.log("我的名字叫"+this.name+",今年已經"+this.age+"歲了");
        }
        return person;//記得返回 不然var per1就是undefined
    }
   var per1 = createObject("翠花",18);
   per1.sayHi();
   var per2 = createObject("萌萌噠",26);
   per2.sayHi();

簡單工廠建立物件

自定義建構函式建立物件

  1. 先自定義建構函式
    根據檢視js系統建構函式Object定義方式

function Object(value){

}

我們根據Object的定義方式進行自定義建構函式


//自定義建構函式
function Person(){
    this.name = "小白";
    this.age = 18;
    this.sayHi = function(){
        console.log("我是"+this.name+"今年"+this.age);
    }
}
  1. 建立物件
    js建立物件 var obj = new Object();
    所以我們也根據js建立物件的方式進行自定義建立物件
//建立物件
var per = new Person();
console.log(per.name);
console.log(per.age);
per.sayHi();
  1. 整個自定義建構函式建立物件程式碼
//自定義建構函式
function Person(){
    this.name = "小白";
    this.age = 18;
    this.sayHi = function(){
        console.log("我是"+this.name+"今年"+this.age);
    }
}
//建立物件
var per = new Person();
console.log(per.name);
console.log(per.age);
per.sayHi();

自定義建構函式建立物件

優化程式碼----------定義引數

    /*  
    1在記憶體中開闢空間,儲存建立新的物件
    2把this設定當前的物件
    3設定物件的屬性和方法的值
    3把this這個物件返回
    自定義建構函式
    */
function Person(name,age){
    this.name = name;
    this.age = age;
    this.sayHi = function(){
        console.log("我是"+this.name+"今年"+this.age);
    }
}
//建立物件
var per = new Person("小盧",18);
console.log(per.name);
console.log(per.age);
per.sayHi();

通過自定建構函式實現下面的例子
建立一個圖片的物件,圖片有寬,有高,有大小(4M),圖片可以展示內容
建立一個小貓的物件,貓有顏色,體重,年齡,小貓可以抓耗子,可以打架

//建立自定義建構函式
function Picture(width,height,size){
    this.width = width;
    this.height = height;
    this.size = size;
    this.show = function (){
        console.log("展示當前圖片的寬度:"+this.width+"高度:"+this.height+"大小:"+this.size);
    }
}
//建立物件
var picture = new Picture("100px","200px","20m");
picture.show();
//建立自定義建構函式
function Smallcat(color,weight,age){
    this.color = color;
    this.weight = weight;
    this.age = age;
    this.seize =function(){
        console.log(this.age+"歲的"+this.color+"的小貓咪體,體重"+this.weight+"可以去抓耗子,可以去打架了");
        
    }
}
//建立物件
var smallcat = new Smallcat("綠色","3kg",3);
smallcat.seize();