JavaScript-调用function的4种方法
Function in JavaScript 有多种调用方式。 你可以选择合适的调用方式。
Javascript can be called:
1. 作为函数
2. 作为方法
3. 作为构造函数
4. 通过call 和apply
1. 作为函数,是最常见的方式,比如再web page里面通过按钮 click event调用。
Javascript can be called:
1. 作为函数
2. 作为方法
3. 作为构造函数
4. 通过call 和apply
1. 作为函数,是最常见的方式,比如再web page里面通过按钮 click event调用。
<button onclick="sayHello()">say hello</button> <script> function sayHello() { console.log(this); console.log(arguments); console.log('hello'); } </script>
As you can see, the value of this is the Window object.
That is the context in which our nifty little function is executing.
You do have the option to force the context of this to be undefined in this case. 强制 上下文 为 undefined.
To do so, you simply add the ‘use strict’; directive to your code.
<button onclick="sayHello()">say hello</button> <script> 'use strict'; //force the context to be undefined function sayHello() { console.log(this); console.log(arguments); console.log('hello'); } </script>
The arguments parameter in this instance does not have any values since no parameters were passed to the function.
2. 作为一个方法method被调用
In order to call a function as a method, it must be defined as a property on an object. Let's look at some code.
作为一个方法,那他必须是一个对象的属性。
2. 作为一个方法method被调用
In order to call a function as a method, it must be defined as a property on an object. Let's look at some code.
作为一个方法,那他必须是一个对象的属性。
<button onclick="greeter.sayHello()">say hello</button> <script> greeter = { sayHello: function () { console.log(this); console.log(arguments); console.log('hello'); } }
3. 作为构造函数被调用
constuctor 意味着 通过一个object设置一些初始化的state。我们调用这个函数通过intent of creating something new and getting it back. 我们调用它们是为了创建新的
<input type="text" id="name"></input> <button onclick="sayHello()">say hello</button> <script> function Greeter(name) { console.info('begin constructor'); console.log(this); console.log(arguments); this.name = name; console.info('end constructor') } function sayHello() { var name = document.getElementById('name').value; var grtr = new Greeter(name); console.log('hello ' + grtr.name); } </script>
4. Calling a function via call and apply
当使用function时候要牢记,他们是first-class objects.
意味着一个function能够拥有自己的属性和方法。
一个函数function拥有自己的方法!!!
call和apply方法就是2中这中方法。
call和apply方法允许你specify the context in which the function will execute.
他们允许你去设置这个value。
Let's take a look at a code example.
<button onclick="go()">GO</button> <script> var people = []; var name = 'alex'; function Person(idx) { idx % 2 === 0 ? this.name = 'alex ' + idx : this.name = 'bob ' + idx; } function printName() { console.log(this.name); } function go() { //call printName to print the name variable defined on the window object printName(); //populate the people array with a couple of people for (let idx = 0; idx < 5; idx++) { people.push(new Person(idx)); } // lets call the printName for each object that we just created // seting this dynamically people.forEach(p => { printName.call(p); }); // printName.call(valueOfThis, 1, 2, 3); // printName.apply(valueOfThis, [1, 2, 3]) } </script>
In this code, we start by defining a couple of variables. An empty array that we will populate with a couple of Person objects and a name.
代码里面首先声明一些变量,一个空数组和一个name
We then have the constructor for the Person object. All it does is choose a name based on the index that is passed to it.
然后有一个Person对象的构造函数,只是根据参数带进来的数的奇偶数选择名字。
Next, we have the printName() function. It simply prints whatever value is in the name variable of whatever object is set to the current context. And finally, we have the go() function that is executed when the user presses the button.
接下来是printName()函数。他的功能就是打印whatever object is set to the current context (被设置为当前上下文的对象的name)的name。 当press the button, 那go() function被执行。
接下来是printName()函数。他的功能就是打印whatever object is set to the current context (被设置为当前上下文的对象的name)的name。 当press the button, 那go() function被执行。
The first thing we do when the button is clicked is call printName() directly.
If you recall from earlier in this post, this is calling a function as a function.
As a result, the context is the global window object and the name ‘alex’ is printed to the console. So far, so good.
button被点击,会直接先调用 printName.
如果您回想一下本文前面的内容,这是将函数作为函数调用。
这个上下文is全局的 window object, the name ‘alex’ is printed to the console.
If you recall from earlier in this post, this is calling a function as a function.
As a result, the context is the global window object and the name ‘alex’ is printed to the console. So far, so good.
button被点击,会直接先调用 printName.
如果您回想一下本文前面的内容,这是将函数作为函数调用。
这个上下文is全局的 window object, the name ‘alex’ is printed to the console.
Next, we set up a for loop and create 5 Person objects and push them into the people array.
我们设置一个循环去创建5个Person 对象,然后push them into the people array.
我们设置一个循环去创建5个Person 对象,然后push them into the people array.
Then we jump right into an array.forEach on our people array. During each iteration, we call printName.call() passing the current object as the context.
This means that we are setting the context of the function dynamically. Pretty cool. This produces the following output in the console.
然后我们jump right into 一个array。
forEach on our people array.
在每个iteration, we call printName.call() 传提给当前对象作为 context
那意味着,我们设置context of the function dynamically. 动态的设置了function的上下文。
This means that we are setting the context of the function dynamically. Pretty cool. This produces the following output in the console.
然后我们jump right into 一个array。
forEach on our people array.
在每个iteration, we call printName.call() 传提给当前对象作为 context
那意味着,我们设置context of the function dynamically. 动态的设置了function的上下文。

output for our dynamically set context
The first ‘alex’ in the output is from our earlier call to printName(). Each additional line of output is from iterating over the array.
This code demonstrates the call() method available on all functions. It looks very similar to object dot syntax because it is object dot syntax. All functions in JavaScript are objects.
The apply method is very similar. The only difference between the two is the arguments they accept.
call() accepts a list of values while
apply() accepts an array, like so:
call() accepts a list of values while
apply() accepts an array, like so:
//call accepts a list of values printName.call(valueOfThis, 1, 2, 3); //apply accepts an array of values printName.apply(valueOfThis, [1, 2, 3]);
That wraps up this quick introduction of the 4 ways to call a JavaScript function.
I find that I use all of these methods and knowing what’s happening under the hood is really helpful.
我发现我使用了所有这些方法,知道引擎盖下发生了什么真的很有帮助。
Keep in mind that in JavaScript, functions are first-class objects. 函数是一类对象 They can have their own properties and methods and can be passed around just like other objects.
This concept of functions as objects can take a bit of getting used to if you’re coming from another language like C# or Java. 花点时间习惯
如果您来自其他语言,如C#或Java,那么函数作为对象的概念可能需要一些时间才能习惯。
I know it took me a little bit to get my head wrapped around it.
我知道我花了一点时间才弄明白
This concept of functions as objects can take a bit of getting used to if you’re coming from another language like C# or Java. 花点时间习惯
如果您来自其他语言,如C#或Java,那么函数作为对象的概念可能需要一些时间才能习惯。
I know it took me a little bit to get my head wrapped around it.
我知道我花了一点时间才弄明白
Thanks for reading.
阅读量: 649
发布于:
修改于:
发布于:
修改于: