-
函数与方法中的this
//对象中的函数叫方法,方法中的this是当前对象 其它普通函数的this一般是window let obj = { site:'baidu', show:function(){ console.log(this);//this指当前对象 function render (){ console.log(this);//this指window } render() } } obj.show()
-
利用map函数的第二个参数改变this
//let lesson = { // site:'baidu', // list:['js','css','java'], // show:function(){ // console.log(this);//当前对象 // this.list.map(item=>{ // console.log(this);//当前对象,箭头函数的作用 // }) // } //} // let lesson = { // site: 'baidu', // list: ['js', 'css', 'java'], // show: function () { // console.log(this);//当前对象 // this.list.map(function(item) { // console.log(this);//window // }) // } // } // let lesson = { // site: 'baidu', // list: ['js', 'css', 'java'], // show: function () { // console.log(this);//当前对象 // this.list.map(function (item) { // console.log(this);//map第二个参数即为匿名函数的this,这里把对象中的this传递给匿名函数的this // },this) // } // } let lesson = { site: 'baidu', list: ['js', 'css', 'java'], handleEvent:function(event){ console.log(this); console.log(111); }, show:function(){ let button = document.querySelector('button'); //通过下面的点击事件系统会自动调用handleEvent方法 button.addEventListener('click',this)//另外这里的this值的是button对象,因为第二个参数(函数就相当于对对象的属性) //button.οnclick= function(){} } } lesson.show()
-
普通函数和构造函数还有对象
//普通函数(工厂函数)一般需要返回值,普通函数中不能使用this function user(name,age){ return { name,//对象的key和value一样,可以简写 age, show(){ console.log(this.name+`-good`); } } } let me = new user('parade') me.show() let you = user('henry') you.show() //构造函数一般首字母大写,且不需要返回值,构造函数中可以使用this function Person(name){ this.name = name; this.show = function(){ } } let p = new Person('herry')//会自动返回创建的对象赋值给p console.log(p); //------------------------------------------------------------------------------------// let u = { name: 'parade', show() { console.log(this.name); } } u.show()//parade function show(params) { bias: 'parade';// } console.log(show.bias);//undefined //-----------------------------------------------------------------------------------//
来源:CSDN
作者:parade岁月
链接:https://blog.csdn.net/parade0393/article/details/103646413