JavaScript, 5 species call the function
This article describes in detail the various Javascript function call method and its principle for understanding the function of JavaScript there is a great help!
Again and again, I found that those who have bug because the Javascript code is not really understanding how the Javascript function is a result of job (By the way, much as the code is written by me). JavaScript has a function of the characteristics of programming , when we select the face of it, this will be hampered our progress.
As a beginner, we have to test five kinds of function call method, from the surface we will consider those who function with C # in the function's role is very similar to, but we can see that while there is still very important to different places, and to overlook these differences will undoubtedly result in difficulty in tracking the bug.
First, let us create a simple function, this function will be used below, this function only return the current value of this and to provide two parameters.
<script type="text/javascript">
function makeArray(arg1, arg2){
return [ this, arg1, arg2 ];
}
</script> The most commonly used method, but unfortunately, the overall function call <br /> When we Javascript study, we learned how to use grammar in the example above to define the function.
, We also know that calling this function is very easy, we need only to do is:
makeArray('one', 'two');
// => [ window, 'one', 'two' ] Wait a minute. What's that window object doing there? Why is it the value of this? If you haven't stopped to think about it, please stay with me here.
Wait a moment, the Window object at doing it here, why this value is that it does, if you had not stopped to consider this question, then please let me one up analysis,
In Javascript, I did not refer to a specific browser, there is a global object, those who look at your script scattered in every line of code (such as at an object outside the statement) in fact have been written on a global object of in the context. In our example, the fact that it can be said makeArray function is not a loose global function, but the overall object of a method, let us look back browser, in this environment it is the overall object is mapped to the window object. Let us prove:
alert( typeof window.methodThatDoesntExist ); // => undefined alert( typeof window.makeArray); // => function
All of these mean that we call makeArray way before and are following the same method call
window.makeArray('one', 'two');
// => [ window, 'one', 'two' ] I say call the most common method is unfortunate because it leads us to default function declarations are the overall situation. We all know the overall situation is not a member of programming best practices. This is a special JavaScript in correctly, avoid using JavaScript at members of the overall situation, you will not regret it.
JavaScript function call rule 1
In the absence of the owner of the object through a clear and direct function calls, such as myFunction (), will lead to become the default value of this object (in your browser window).
Function call <br /> Let us now create a simple object, use makeArray function as one of its methods, we will use json way to declare a target, we have to call this method
//creating the object
var arrayMaker = {
someProperty: 'some value here',
make: makeArray
};
//invoke the make() method
arrayMaker.make('one', 'two');
// => [ arrayMaker, 'one', 'two' ]
// alternative syntax, using square brackets
arrayMaker['make']('one', 'two');
// => [ arrayMaker, 'one', 'two' ] See here is different now, this value has become the object itself. You may doubt the original function definition has not changed, why it is not the case window. All right, this is in the transmission function at JSavacript way, function in JavaScript it is a standard data types, the exact Say yes to an object. you can transfer them or copy them. as if the entire function of several parameters of body function list and have been copied, and was assigned to the arrayMaker property in the make, It seems to me that it would define a arrayMaker:
var arrayMaker = {
someProperty: 'some value here',
make: function (arg1, arg2) {
return [ this, arg1, arg2 ];
}
}; JavaScript function call rule 2 in a method call using the grammar, such as obj.myFunction () or obj [ 'myFunction'](), then this value for obj
This is the code in the case deal with a major source of bug, take a look at these examples
<input type="button" value="Button 1" />
<input type="button" value="Button 2" />
<input type="button" value="Button 3" />
<script type="text/javascript">
function buttonClicked(){
var text = (this === window) ? 'window' : this.id;
alert( text );
}
var button1 = document.getElementById('btn1');
var button2 = document.getElementById('btn2');
button1.onclick = buttonClicked;
button2.onclick = function(){ buttonClicked(); };
</script> Click the first button will be displayed "btn" because it is a method call, this for their object (button elements) click the second button will display the "window" because buttonClicked are directly call (unlike obj.buttonClicked ( ).) This is the third button with us, will deal with case where function directly on the tag are the same. so click the button the results of the third and second are the same.
The use of JS libraries like jQuery has the advantage of this, when at jQuery in case defines a function handle, JS library will help to rewrite the value of this to ensure that it contains elements of the current source case cited,
//使用jQuery
$('#btn1').click( function() {
alert( this.id ); // jQuery ensures 'this' will be the button
}); jQuery is how the value of this heavy-duty ones? continue reading
The other two: apply () and call ()
The more you use the JavaScript function, the more you find that you have the required transfer function and in different contexts where they call, just like in the case Qjuery function in treatment done, you tend to always need to reset this value . Remember you told me, in Javascript function is in the target function object contains a number of predefined methods, there is one of two that apply () and call (), we can use them to reset this.
var gasGuzzler = { year: 2008, model: 'Dodge Bailout' };
makeArray.apply( gasGuzzler, [ 'one', 'two' ] );
// => [ gasGuzzler, 'one' , 'two' ]
makeArray.call( gasGuzzler, 'one', 'two' );
// => [ gasGuzzler, 'one' , 'two' ]These two methods are similar and different parameters of the back are different, Function.apply () is to use an array to pass to the function, and Function.call () are independent of these parameters will be passed, in practice you will find that apply () in most cases more convenient.
Rules JSavacript function call at 3 if we do not want to copy the function to a method and want to overload this value, we can use myFunction.apply (obj) or myFunction.call (obj).
Constructor <br /> I do not want in-depth study of the type of Javascript at the definition, but at the moment, we need to know there is no category at Javascript, and any type of a custom requires a initialization function, use the prototype object (as the initial function of a property) you the type of definition is also a good, and let us to create a simple type
//声明一个构造器
function ArrayMaker(arg1, arg2) {
this.someProperty = 'whatever';
this.theArray = [ this, arg1, arg2 ];
}
// 声明实例化方法
ArrayMaker.prototype = {
someMethod: function () {
alert( 'someMethod called');
},
getArray: function () {
return this.theArray;
}
};
var am = new ArrayMaker( 'one', 'two' );
var other = new ArrayMaker( 'first', 'second' );
am.getArray();
// => [ am, 'one' , 'two' ] A very important and it is worth noting that appear in the function call in front of the new operator, does not that, you function as the same global function and property of those we have created will be created on the global object (window), and you do not want to do, and the other topic is because you do not have the constructor return value, so if you forget to use new operator, you will lead a number of variables have been assigned for the undefined. For this reason, the constructor function to uppercase letters at the beginning is a good habit, this can serve as a reminder, so you call at the time not to forget in front of new operators.
With such a careful initialization function in the code and you write in other languages of the initialization function is similar. This will be the value you will create the object.
Javascript function call when the 4 rules you will function when used as a initialization function, such as MyFunction (), Javascript run-time will be designated as the value of this new object.
<br /> Summarize my understanding of the function call hope that differences in the way you would Sjavacript code away from the bugs, some of this kind of bug will ensure that you always know the value of this first step is to avoid them
Original:
Translator: Luke







