函數進階

構造函數

瀏覽器中有內置的九個原生構造函數對象
Boolean
String
Number
Object
Function
Array
Date
RegExp
Error

構造函數與普通函數區別

  • 本質上是沒有區別,從語法上來講。普通函數也可以當作構造函數來使用
  • 構造函數通常會有this指定實例屬性,原型對象上通常有一些公共方法
  • 構造函數命名通常首字母大寫
  • -
此例子中對需要隱藏的屬性 status  和light 進行了隱藏
不能直接通過對象訪問
var Car = (function{
    var status = "stop";
    var light = "off"
    return function(type, color){
        this.type = type;
        this.color = color;
    }
})();
Car.prototype.stop = function(){
    this.stop = "stop";
    this.light = "off";
    console.log(this.type + "is" + this.status);
}
Car.prototype.start = function(){
    this.stop ="driving";
    this.light = "on";
    console.log(this.type + "is" + this.status);
}

var audi = new Car("adui", "sliver");
var benz = new Car("benz", "black");

audi.start();

函數調用(this)

調用可以分爲四類:
.構造函數調用模式:var adui = new Car("audi", "sliver"); 
.方法調用模式
.函數調用模式
.apply(call)調用模式

函數構造調用模式

如下程序

var Car = (function{
    var status = "stop";
    var light = "off"
    return function(type, color){
        this.type = type;//var audi = new Car("adui", "sliver")時 this 爲audi對象
        this.color = color;
    }
})();
Car.prototype.stop = function(){
    this.stop = "stop";
    this.light = "off";
    console.log(this.type + "is" + this.status);
}
Car.prototype.start = function(){
    this.stop ="driving";
    this.light = "on";
    console.log(this.type + "is" + this.status);
}

var audi = new Car("adui", "sliver");//構造函數調用模式

注:這種調用模式中,**構造函數內部**的this對象指向被創建的調用對象,此例子中的Car構造函數中的this就指向audi這個對象

方法調用模式

概念:對象調用方法,比如本例中的audi.start();就爲方法調用模式,而start()方法中的this值就爲audi

var Car = (function{
    var status = "stop";
    var light = "off"
    return function(type, color){
        this.type = type;
        this.color = color;
    }
})();
Car.prototype.stop = function(){
    this.stop = "stop";
    this.light = "off";
    console.log(this.type + "is" + this.status);
}
Car.prototype.start = function(){
    this.stop ="driving";//audi.start()時this對象指向audi對象
    this.light = "on";
    console.log(this.type + "is" + this.status);
}

var audi = new Car("adui", "sliver");//構造函數調用模式
audi.start();//方法調用模式

函數調用模式

在函數內部定義的子函數,它的this對象爲window對象,而不是它的上級對象

//函數調用模式
function add(i, j){
    return i+j;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章