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

介绍: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)无关紧要.在本例中不使用.

转载于:https://www.cnblogs.com/zienzir/p/9255203.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值