Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

箭头函数this指向demo #72

Open
Kelichao opened this issue Feb 24, 2021 · 0 comments
Open

箭头函数this指向demo #72

Kelichao opened this issue Feb 24, 2021 · 0 comments

Comments

@Kelichao
Copy link
Owner

	window.aaa = {
		  name:"window",
		  b :() => {
		    console.log(this.name,11111)
		  },
		  c: {
		    name:"c",
		    d: () => {
		      console.log(this.name,222222)
		    }
		  },
		  cc: {
		    name:"cc",
		    dd: () => {
		      console.log(this.name,444)
		    }
		  },
		  e: {
		    name:"e",
		    f ()  {
		      console.log(this.name,333)
		    }
		  }
		}
		
		aaa.b(); // window 11111
		aaa.c.d();// window 222222
		aaa.cc.dd()
		aaa.e.f();// e 333
		
		
		
		(function() {
		
			var aaa = {
			  name:"aaa",
			  b :() => {
			    console.log(this.name,11111)
			  },
			  c: {
			    name:"c",
			    d: () => {
			      console.log(this.name,222222)
			    }
			  },
			  cc: {
			    name:"cc",
			    dd: () => {
			      console.log(this.name,444)
			    }
			  },
			  e: {
			    name:"e",
			    f ()  {
			      console.log(this.name,333)
			    }
			  }
			}
			
			aaa.b.call(aaa); // window 11111
			
			aaa.c.d();// window 222222
			aaa.cc.dd()
			aaa.e.f();// e 333
			
			
			console.log(aaa.name)
			
			
		})()
		
		
		
		
		class BBB{
			constructor(){
				this.name = "BBB"
			}
			
			
		}
		Object.assign(BBB.prototype, {
		    ddd:() => {
		    	console.log(this.name)
		    }
		})
		var bbb = new BBB()
		bbb.ddd();
		
		
		
		
		 var x = ()=> {
					// ccc
					var s = {
						a:() => {
							console.log(this)
						}
					}
					
					s.a();
				}
				
				
		// 剪头函数父级的正确指向。
		var ccc = {
			a:function() {
				// ccc
				var s = {
					a:() => {
						console.log(this)
					}
				}
				
				s.a();
			},
			b:x
		}
		
		ccc.a();/// ccc
		ccc.b();// window  函数放在对象里面跟放在对象外面完全不同
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant