apply bind call写一些案例代码
时间: 2023-09-14 07:09:48 浏览: 104
【JavaScript源代码】JavaScript函数之call、apply以及bind方法案例详解.docx
1. 使用apply调用函数,并传递参数
```javascript
function greeting(name) {
console.log(`Hello, ${name}!`);
}
greeting.apply(null, ['John']);
// 输出:Hello, John!
```
2. 使用bind绑定函数this值
```javascript
const person = {
name: 'John',
age: 30,
greeting: function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
const sayGreeting = person.greeting.bind(person);
sayGreeting();
// 输出:Hello, my name is John and I'm 30 years old.
```
3. 使用call调用函数,并传递参数
```javascript
function greeting(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: 'John'
};
greeting.call(person, 'Mary');
// 输出:Hello, Mary! My name is John.
```
4. 使用apply绑定函数this值和传递参数
```javascript
function greeting(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: 'John'
};
greeting.apply(person, ['Mary']);
// 输出:Hello, Mary! My name is John.
```
阅读全文