实现call js
调用 JavaScript 函数的方法
在 HTML 中嵌入 JavaScript 代码,通过 <script> 标签直接调用函数:
<script>
function myFunction() {
alert("Function called!");
}
myFunction(); // 直接调用
</script>
通过事件触发调用 JavaScript 函数,例如按钮点击:
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
console.log("Button clicked!");
}
</script>
从外部文件调用 JavaScript
创建单独的 .js 文件(如 script.js),在 HTML 中引入并调用:
<script src="script.js"></script>
script.js 文件内容:
function externalFunction() {
alert("External function called!");
}
externalFunction();
使用 call() 和 apply() 方法
call() 方法允许调用函数并指定 this 值:
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
const person1 = {
firstName: "John",
lastName: "Doe"
};
person.fullName.call(person1); // 返回 "John Doe"
apply() 方法与 call() 类似,但参数以数组形式传递:
const numbers = [5, 6, 2, 3, 7];
Math.max.apply(null, numbers); // 返回 7
立即调用函数表达式 (IIFE)
定义后立即执行的函数:
(function() {
console.log("IIFE executed immediately");
})();
使用 setTimeout 或 setInterval 延迟调用
延迟指定时间后调用函数:
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
定期重复调用函数:
setInterval(function() {
console.log("Executed every 1 second");
}, 1000);
通过 Promise 或 async/await 调用异步函数
使用 Promise 调用异步函数:
function asyncFunction() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Async operation completed");
}, 1000);
});
}
asyncFunction().then(result => console.log(result));
使用 async/await 调用异步函数:

async function callAsync() {
const result = await asyncFunction();
console.log(result);
}
callAsync();






