this 這個功能在JavaScript中充分發揮 var obj = { yes: function(){ // this == obj this.val = true; }, no: function(){ this.val = false; } }; // We see that there is no val property in the 'obj' object alert( obj.val == null ); // We run the yes function and it changes the val property // associated with the 'obj' object obj.yes(); alert( obj.val == true ); // However, we now point window.no to the obj.no method and run it window.no = obj.no; window.no(); // This results in the obj object staying the same (as the context was // switched to the window object) alert( obj.val == true ); // and window val property getting updated. alert( window.val == false ); 以上處理有些不太同一理解,JavaScript提供了call和apply方法實現這個功能: // A simple that sets the color style of its context function changeColor( color ) { this.style.color = color; } // Calling it on the window object, which fails, since it doesn't // have a style object changeColor( "white" ); // Find the element with an ID of main var main = document.getElementById("main"); // Set its color to black, using the call method // The call method sets the context with the first argument // and passes all the other arguments as arguments to the function changeColor.call( main, "black" ); // A function that sets the color on the body element function setBodyColor() { // The apply method sets the context to the body element // with the first argument, the second argument is an array // of arguments that gets passed to the function changeColor.apply( document.body, arguments ); } // Set the background color of the body to black setBodyColor( "black" ); |