<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p> 全局函数 (myFunction) 返回参数参数相乘的结果: </p> <p id="demo"></p> <script> function myFunction(a, b) { return a * b; } document.getElementById("demo").innerHTML = myFunction(10, 2); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>全局函数 myFunction() 会自动成为 window 对象的方法。</p> <p>myFunction() 类似于 window.myFunction()。</p> <p id="demo"></p> <script> function myFunction(a, b) { return a * b; } document.getElementById("demo").innerHTML = window.myFunction(10, 2); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>在 HTML 中 <b>this</b> 的值, 在全局函数是一个 window 对象。</p> <p id="demo"></p> <script> function myFunction() { return this; } document.getElementById("demo").innerHTML = myFunction(); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>myObject.fullName() 返回 John Doe:</p> <p id="demo"></p> <script> var myObject = { firstName:"John", lastName: "Doe", fullName: function() { return this.firstName + " " + this.lastName; } } document.getElementById("demo").innerHTML = myObject.fullName(); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>在一个对象方法中 ,<b>this</b> 的值是对象本身。</p> <p id="demo"></p> <script> var myObject = { firstName:"John", lastName: "Doe", fullName: function() { return this; } } document.getElementById("demo").innerHTML = myObject.fullName(); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p>该实例中, myFunction 是函数构造函数:</p> <p id="demo"></p> <script> function myFunction(arg1, arg2) { this.firstName = arg1; this.lastName = arg2; } var x = new myFunction("John","Doe") document.getElementById("demo").innerHTML = x.firstName; </script> </body> </html>
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var myObject; function myFunction(a, b) { return a * b; } myObject = myFunction.call(myObject, 10, 2); // 返回 20 document.getElementById("demo").innerHTML = myObject; </script> </body> </html>
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var myObject, myArray; function myFunction(a, b) { return a * b; } myArray = [10, 2] myObject = myFunction.apply(myObject, myArray); // 返回 20 document.getElementById("demo").innerHTML = myObject; </script> </body> </html>