日期:2014-05-16 浏览次数:20332 次
<!doctype html> <html> <head> <title> call-apply </title> </head> <body> <input type="text" id="idTxt" value="input text"> <script type="text/javascript"> var value = "global var"; function mFunc() { this.value = "member var"; } function gFunc() { alert(this.value); } window.gFunc(); // show gFunc, global var gFunc.call(window); // show gFunc, global var gFunc.call(new mFunc()); // show mFunc, member var gFunc.call(document.getElementById('idTxt')); // show element, input text </script> <script language="javascript"> var func = new function() { this.a = "func"; } var func2 = function(x) { var a = "func2"; alert(this.a); alert(x); } func2.call(func, "func2"); // show func and func2 </script> </body> </html>
<!doctype html> <html> <head> <title> call - apply for inherit </title> </head> <body> <script type="text/javascript"> function baseA() // base Class A { this.member = "baseA member"; this.showSelfA = function() { window.alert(this.member); } } function baseB() // base Class B { this.member = "baseB member"; this.showSelfB = function() { window.alert(this.member); } } function extendAB() // Inherit Class from A and B { baseA.call(this); // call for A baseB.call(this); // call for B } window.onload = function() { var extend = new extendAB(); extend.showSelfA(); // show A extend.showSelfB(); // show B } </script> </body> </html>
function baseA() // base Class A { this.memberA = "baseA member"; // member改成memberA,以区分baseB中的member this.showSelfA = function() { window.alert(this.memberA); // 显示memberA } }