Four forms of existence of a function:
1. Function form
2. Method form assigns a function to a member of an object, then it is called a method
3. Builder form
4. Contextual patterns
1. Function form:
var foo = function () {
alert (this); This is window
};
2. Method form:
o = {};
O.foo = foo; The Foo attribute that assigns the function Foo to object o
o.foo (); The object is ejected, this is the object
var lib = {
test:function () {
alert (this); This here represents the object (the Lib object itself)
//var that = this; You can do this in the anonymous function (function
() {
alert (this) if this represents a Lib object; The anonymous function here does not belong to the Lib object, so the still representation Window
}) ();
}
;
Lib.test ();
3. Constructor (constructor) var p = new person ();
1, new created the object, and opened up space
2. Pass the reference address of the object to the function and use this to receive
3, the construction method execution end, returns this
var person = function () {
this.age =;
THIS.name = "Mr Jing";
Return ' {} ';
var p = new person ();
alert (p.name); The pop-up is undefined, and because the function returns an object, the object is returned directly to the person, ignoring the Age,name property
var person = function () {
this.age =;
THIS.name = "Mr Jing";
return 123;
};
var p = new person ();
alert (p.name); Pop-up "Mr Jing", because the return value is not an object, so directly ignore the return value
alert (p); Eject Object
The things that change are: the constructor changes the return value of the function; If the return value of the function is an object, it is returned according to the return value, and returned directly if the return value is not an object;
4. Context invocation pattern function . Apply(object, [argument list])
var foo1 = function (A, b) {
alert (this);
Return a > B? a:b;
};
var num = foo1.apply (null, [112,%]); At this point foo1 is the function form, this represents the window
num = foo1.apply ({}, [112,)); At this point foo1 is the method form, this represents the object passed in in the parameter {}
function .call (object, parameter list);
var num1 =foo1.call (null,112,34);
Num1=foo1.call ({},112,34); Except for the argument list, the rest is the same as apply
The above article discusses the JavaScript function four kinds of existence form is the small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.