Use the constructor to create a function, and then use the function in the new way, which is equivalent to creating an object
function User ( name) {
this . name = name;
this . show = function ( ) {
console. log ( this . name) ;
function render ( ) {
console. log ( this ) ;
}
render ( ) ;
} ;
}
let xiaoming = new User ( '小明' ) ;
console. log ( xiaoming. show ( ) ) ;
① In an object, when a function belongs to a certain attribute of the object, then the function is called: method/class method
② If the function in the object does not belong to a certain attribute, then this function is just a function
③This of the method/class method points to the current object
④ This of the function points to the window object
⑤Define a global variable, which is stored in the window object
let obj = {
site: 'https' ,
show: function ( ) {
console. log ( this ) ;
function render ( ) {
console. log ( this ) ;
console. log ( this . name) ;
}
render ( ) ;
} ,
} ;
console. log ( obj. show ( ) ) ;
Extension of this 1
let obj_cart = {
site: 'https://shopCart.com' ,
front: 'world-' ,
lists: [ 'js' , 'html' , 'css' ] ,
show: function ( ) {
const self = this ;
this . lists. map ( function ( value) {
console. log ( value) ;
console. log ( self. front + value) ;
} ) ;
} ,
} ;
console. log ( obj_cart. show ( ) ) ;
Extension of this 2
The situation here is only for some functions
Some callback functions can pass two parameters, then the second parameter will point to the object this to the callback function, you can get the object
let grades = {
class : 'class 4-' ,
mark: [ 11 , 22 , 33 ] ,
appear: function ( ) {
this . mark. map ( function ( item) {
console. log ( this . class + item) ;
} , this ) ;
} ,
} ;
console. log ( grades. appear ( ) ) ;