Simple example of php method call mode and function call mode
Source: Internet
Author: User
In function call mode, this is bound to a global object. In this case, the object attributes and methods are also reflected when they are initialized. An existing function and object are as follows:
Copy codeThe code is as follows:
Var doubling = function (x ){
Return x * 2;
};
Var obj = {
Val: 100,
};
In function call mode, this is bound to a global object. In this case, the object attributes and methods are also reflected when they are initialized. Currently, ojb is supplemented as follows:
Copy codeThe code is as follows:
Var obj = {val: 100,
Prop: function (){
Var that = this;
Document. write ('name: '+ that +'; type: '+ typeof (that) +'
');
Return doublling (that. val );
}(),
Get_prop: function (){
Var that = this;
Document. write ('name: '+ that +'; type: '+ typeof (that) +'
');
Return doublling (that. val );
},
};
Prop uses an anonymous function executed and expects to obtain the result of the doubling () operation in the function call mode when the val value of the object is located. get_prop is the method call mode.
When the script is loaded, when the property prop of obj is initialized, the statement "name: [object Window]; type: object" is output, using obj. when get_prop () is used, the statement "name: [object Object]; type: object" is output. The former indicates that the "this" of the function body is the global variable window, and the latter, if expected, is the obj itself.
You can check the returned values of the property prop and method get_prop (). The former performs multiplication on the window object and returns NaN, and the latter equals to 200.
In addition to the obj literal expression, it is expected to set the new_prop attribute and the new_get_prop () method. The result will be consistent with the previous article, and the method call mode will get the binding of this to itself.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.