this action within function
function math(){
var info = 'info'; //External cannot be obtained directly, becoming a private property
this.name = 'fun1'; //Assigning a value with this makes it possible for the outside to get this value from the object.property, which becomes a public property
this.add = function(a,b){
return a+b;
}
}
var m = new math();//Note the need to create objects with new
console.log(m.info)//Not available
console.log(m.name)//Output fun1
console.log(m.add(1,2))//Output 3
Execute function immediately
(function (formal parameter){ //Code block that executes immediately } (arguments)
As the name implies, immediate execution of a function executes immediately when it is created, without binding any events, being invoked, and without waiting for any action, when it is loaded.function(){} is an anonymous function, followed by () to indicate that the function was called and passed in parameters.
Example:
//Modify the built-in objects of WeChat to share with Wechat
(function(cache_data){
window.wxData = {
img_url : 'http://xxx.xx.jpg',
link : location.href,
title : "Title",
desc : "describe"
};
}(window.cache_data));
closure
The idea of closures is that private variables in a method (class) cannot be accessed directly from outside, but can only be accessed and manipulated through the method's internal methods.
Example:
$(function(){
var result = outter();//Result equals the result of outter execution, that is, it points to Inner function
result();//Essentially for calling Inner functions
result();//When Inner() is called multiple times, the same a object is accessed internally by the function, so the output is: 1, 2, 3
result();
console.log('------Direct Access outter private variable------');
console.log(outter.a);//Direct access is inaccessible, and a becomes the real internal variable of outter
var product = new Product();
product.setName("Commodity 1");
product.setPrice(9.99);
console.log(product.getName()+" --- "+product.getPrice());
});
function outter(){
var a = 0;
function inner(){
a += 1;
console.log(a);
}
return inner;
}
//Another form of closure, the usual bean object form
//Product private variables cannot be accessed directly from outside, they can only be manipulated through Setter and getter, Product internal functions access the same private variable
function Product(){
var name;
var price;
this.setName = function(val){
name = val;
}
this.getName = function(){
return name;
}
this.setPrice = function(val){
price = val;
}
this.getPrice = function(){
return price;
}
}
Another, more complex situation, which is often asked during interviews, is to understand that only an object name followed by () can actually call the function that the object points to
function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = function(){//result[i] all points to a function, because the function has not been called yet, so the same object I is returned inside the function
return i;
};
}
return result;
}
var funcs = createFunctions();
//here
//result[0] = function(){return i}
//result[1] = function(){return i}
//result[2] = function(){return i}
//.... And i equals 10 at the end of the createFunctions internal loop
for (var i=0; i < funcs.length; i++){
console.log(funcs[i]());//This is when the internal function is actually called
}
prototype
Each function (class) has a prototype property that can be used to dynamically add methods to the function.
$(function(){
//Bind toString method for Product function
Product.prototype.toString = function(){
return {
name:this._name,
price:this._price,
info:'prototype Is the method for binding functions (classes)'
}
}
var p1 = new Product('Commodity 1',8.88);
var p2 = new Product('Commodity 2',9.99);
console.log(p1.toString());//Call toString()
console.log(p2.toString());
});
function Product(name,price){
this._name = name;
this._price = price;
}
Modularization
Put forward and encapsulate ideas.Based on the immediate execution of functions, access to variables and methods within the module can be controlled, and a large number of modular statements are used by most frameworks into jQuery.
var module = (function(Formal parameters) {
//Internal Variables and Methods
//Expose methods or properties as return ed objects for external invocation
return{
}
})(Arguments);
The method inside the module does not execute immediately, only when called externally, and the parameter argument can be empty.
Example:
$(function() {
//Invoke the properties or methods provided by the module
console.log(module.description);
module.introduce('blysin');
module.printParam();
});
//Create a modular code
var module = (function(param) {
var name = "module"; //private attribute
function print(val) { //private method
console.log('Called print Method, output:' + val);
}
function introduce(user) { //private method
var words = user + 'is useing ' + name;
print(words);
}
function printParam(){
console.log(param);
}
//The purpose of return is to expose private methods or properties to the outside for external invocation
return {
description: "This is a simple "+name, //Expose an attribute
introduce: introduce,//Expose a method
printParam:printParam
}
})({
status:'normal',
isDebug:true
});
apply, call, and bind methods (based on object (json)
JavaScript developers need to understand the differences between apply, call, and bind methods.What they have in common is that the first parameter is this, which is the context on which the function runs.
Of the three, the call method is the simplest, which is equivalent to calling a function with a specified value of this:
obj1.method.call(obj2,arg1,arg2...);
Execution effect: Let the obje2 object execute a method within the obj1 object, and arg is the parameter of the method.
var user = {
name: "Rahul Mhatre",
whatIsYourName: function() {
console.log(this.name);
}
};
user.whatIsYourName(); // Output "Rahul Mhatre",
var user2 = {
name: "Neha Sampat"
};
user.whatIsYourName.call(user2); // Output "Neha Sampat"
The apply method is similar to the call method.The only difference is that the apply method uses arrays to specify parameters, while the call method specifies each parameter individually:
- apply(thisArg, [argsArray])
- call(thisArg, arg1, arg2, ...)
var user = {
greet: "Hello!",
greetUser: function(userName) {
console.log(this.greet + " " + userName);
}
};
var greet1 = {
greet: "Hola"
};
user.greetUser.call(greet1, "Rahul"); // Output "Hola Rahul"
user.greetUser.apply(greet1, ["Rahul"]); // Output "Hola Rahul"
Using the bind method, this value can be bound to a function and returned as a new function:
var user = {
greet: "Hello!",
greetUser: function(userName) {
console.log(this.greet + " " + userName);
}
};
var greetHola = user.greetUser.bind({greet: "Hola"});
var greetBonjour = user.greetUser.bind({greet: "Bonjour"});
greetHola("Rahul") // Output "Hola Rahul"
greetBonjour("Rahul") // Output "Bonjour Rahul"