如何在 JavaScript 中借用方法?
可以使用 call()、apply() 和 bind() 在 JavaScript 中借用方法。
以下是用于在 JavaScript 中借用方法的代码 -
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document<title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Borrowing a method in JavaScript</h1> <div class="sample"></div> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to borrow the welcome method of object obj </h3> <script> let sampleEle = document.querySelector(".sample"); let resultEle = document.querySelector(".result"); let obj = { firstName: "Rohan", lastName: "Sharma", welcome() { return "Welcome " + this.firstName + " " + this.lastName; }, }; let obj1 = { firstName: "John", lastName: "Shaw", }; sampleEle.innerHTML = "obj.welcome() = " + obj.welcome(); document.querySelector(".Btn").addEventListener("click", () => { resultEle.innerHTML = "obj1.welcome() = " + obj.welcome.call(obj1); }); </script> </body> </html>
输出
上述代码将产生以下输出 -
点击“点击此处”按钮 -
广告