javascript:Functions (1)

來源:互聯網
上載者:User

函數對象 Function Object

函數就是對象。對象字面量產生的對象連結到Object.prototype。函數對象連結到Function.prototype。每個函數在建立時附有兩個附件的隱藏屬性:函數的上下文和實現函數行為的代碼。

函數字面量 Function Literal

函數對象可以通過函數字面量來建立。

var add = function(a, b){return a+b;};

調用 Invocation

除了聲明時定義的形式參數,每個函數接收兩個附加的參數:this 和arguments。

this在物件導向編程中非常重要,它的值取決於調用的模式。在JS中,一共有四種調用模式,這些模式在初始化參數this上存在差異。

1、方法調用模式

2、函數調用模式

3、構造器調用模式

4、apply調用模式

方法調用模式 The Mehtod Invocation Pattern

當一個函數被儲存為一個對象的屬性並且被調用時,this綁定到該對象。

通過this可取得他們所屬對象的內容相關的方法稱為公用方法。

var myObject = {
value : 0,
increment:function(inc)
{
this.value += (inc);
}
};
myObject.increment(3);
myObject.increment(3);
alert(myObject.value);//result is 6.

函數調用模式 The Function Invocation Pattern

在函數調用模式下,this被綁定到全域對象上。這個是javascript語言設計上的一個錯誤。

看如下code:

var g='globle';
var o=function()
{
var g= 'self';
alert(this.g);
}();
//result is 'globle'. it is not correct.

可以採用以下方法避免

var g='globle';
var o=function()
{
var that = this;
that.g='self';
alert(this.g);
}();
//result is 'self', it is correct.

構造器調用模式 The Consultant Invocation Pattern

js是居於原型繼承的語言,所以對象可以從其他對象直接繼承屬性。該語言是無類別的。

如果一個函數前面帶上new來調用,那麼將建立一個隱藏連結到該函數的prototype成員的新對象,同時this將會被綁定到那個新對象上。

不推薦使用這種方法。

var Quo=function(string)
{
this.status =string;
};
Quo.prototype.get_status = function(){return this.status;};
var myQuo = new Quo("Confused");
alert(myQuo.get_status());
//new could not be lost.

Apply調用模式 The Apply Invocation Pattern

通過apply/call方法調用函數,其中第一個參數為我們指定的this的值。

var  statusObject = {status : 'A-OK'};
var status = Quo.prototype.get_status.apply(statusObject);
//result is 'A-OK';the first param is "this" value.
相關文章

聯繫我們

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