Now I will bring you an article about the four existence forms of JavaScript functions. Let me share it with you now and give it as a reference for everyone.
The four existence forms of functions:
1. Function form
2. Method form assigns a function to a certain A member of an object is called a method
3.Constructor form
4.Context form
1.Function form:
var foo = function() { alert(this); //this是window };
2. Method form:
o = {}; o.foo = foo; //将函数foo赋值给对象o的foo属性 o.foo(); //弹出的是object,此时的this表示object
var lib = { test:function() { alert(this); //此处的this表示object(lib对象本身) //var that = this; //要想匿名函数中this表示lib对象,可以这样 (function() { alert(this); //此处的匿名函数不属于lib对象,所以this的任然表示window })(); } }; lib.test();
3. Constructor (constructor) var p = new Person();
1. new creates the object and opens up space.
2. Pass the reference address of the object to the function and use this to receive it in the function.
3. The constructor method ends and returns this
var Person = function() { this.age = 19; this.name = "Mr靖"; return "{}"; }; var p = new Person(); alert(p.name); //弹出的是undefined,由于函数返回的是一个对象,所以直接将这个对象返回给person,而忽略age,name属性
var Person = function() { this.age = 19; this.name = "Mr靖"; return 123; }; var p = new Person(); alert(p.name); //弹出“Mr靖”,由于返回值不是对象,所以直接忽略返回值 alert(p); //弹出object
The changed things are: the constructor changes the return value of the function; if the return value of the function is an object, then it is returned according to the return value; if the return value is not an object, the return value is ignored and directly Return this;
4. Context call mode function.apply(Object, [parameter list])
var foo1 = function(a, b) { alert(this); return a > b ? a : b; }; var num = foo1.apply(null, [112, 34]); //此时foo1是函数形态,this表示window num = foo1.apply({}, [112, 34]); //此时foo1是方法形态,this表示参数中传入的对象{}
Function.call(Object, parameter list);
var num1 =foo1.call(null,112,34); num1=foo1.call({},112,34); //除了参数列表外,其余和apply一样
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Learn more about the basic content of JavaScript Array objects
How to use the JavaScript eval() function correctly
Native javascript AJAX three-level linkage implementation code
The above is the detailed content of Detailed interpretation of the four existence forms of JavaScript functions (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!