[JavaScript-Function] Function Invocation/Call(函數調用) 以及call() and apply() 方法

來源:互聯網
上載者:User

標籤:沒有   call()   style   str   pre   nbsp   HERE   win   調用   

介紹:JS函數中的代碼會被函數被invoke(調用)時執行.

函數被定義時代碼不執行,

函數調用時函數內的代碼會被執行.

常用的term是 call a function 而不是 invoke a function.

function always belong to a object in javascript.

When a function does no tbelong to nay object. In javascript there is alaways a default global object.

在Html 中,是瀏覽器視窗本身. the global object will become a window function in this case.

That means it can be invoked by window.functionName().

1. this keyword : 代表當前代碼的對象.

The value of this, when used in a function , is the objec that owns the function.

Note that this is not a variablke. It is a keyword. You cannot change the value of this.

 

2. Invoking a Function as a Method

In javascript you can defiune functions as object methods.(對象方法?),形如:

var myObject = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
myObject.fullName();         // Will return "John Doe"

3. 對於JSON對象,可以使用"."來調用對象內方法.

var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName+" "+this.lastName;
}
}

4.Invoking a Function with a Function Constructor

NOTE:

A constructor invocation creates a new object. The new object inherits the properties and methods from its constructor.

The this keyword in the constructor does not have a value.
The value of this will be the new object created when the function is invoked.

====================================Call==================================

 

 

All Functions are Methods:If a function is not a method of a JavaScript object, it is a function of the global object (see previous chapter).

1. The JavaScript call() method.

2. The call() method with Arguments.

Output:

John Doe,Oslo,Norway

 

 =======================apply()=================

和call()方法類似.

區別是,call() 的參數是分隔開的, apply()的參數是一個數組.

person.fullName.call()變成了person.fullName.apply(person1,["Oslo","Norway"]);

====執行個體 Math.max(arg1,arg2,arg....)

Math.max(1,2,3);會返回3

但是JavaScript數組並沒有max()方法,所以可以apply Math.max()方法.

Math.max.apply(null, [1,2,3]); // Will also return 3

 第一個參數(null)無關緊要.在本例中不使用.

[JavaScript-Function] Function Invocation/Call(函數調用) 以及call() and apply() 方法

相關文章

聯繫我們

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