js面试题
知识点
1.js面向对象 function Func(name,age){ this.Name = name; this.Age = age } obj = new Func('alex',18) 2.this关键字 #每个函数都有this #函数调用时,this=window #类new时,this=obj function func(name,age){ #当做函数执行时,this=window console.log(this); } func() function Func(name,age){ #当做函数执行时,this=window console.log(this); } obj = new Func() 3.js中无字典,只有对象 Name='alex'; obj = { Name:'root', Age:18, Func:function(){ #this=obj console.log(this.Name) #root var that=this function inner(){ #this=window #that=obj console.log(this.Name) #alex console.log(that.Name) #root } inner() //自执行函数 (function(){ console.log(this.Name) }() }, } 相当于new了对象obj
面试题
js面试题: 题目1. 代码在执行之前,作用域已经创建 var v = 123; function foo(){ var v = 456; function inner(){ console.log(v); } return inner; } var result = foo() console.log(result) console.log(result()) 问输出结果? ƒ inner(){ console.log(v); } 456 题目2.js面向对象 Name = 'root'; Age = 18; function Foo(name,age){ this.Name = name; this.Age = age; this.Func = function(){ //this=obj console.log(this.Name,this.Age); (function(){ //this=window console.log(this.Name,this.Age); })(); } } obj = new Foo('alex',666); obj.Func(); 问输出结果? alex 666 root 18 题目3:作用域 var name = '女神' function Foo(name,age){ this.name = name; this.age = age; this.getName = function(){ console.log(this.name); # 屌丝 var that = this (function(){ console.log(that.name); # 屌丝 })() } } obj = new Foo(“屌丝”',19) obj.getName() 题目4:实例化对象 var name = '女神' obj = { name:'屌丝', age: 19, getName:function(){ console.log(this.name); # 屌丝 var that = this (function(){ console.log(that.name); # 屌丝 })() } } obj.getName()