【JavaScript】JavaScript面试题1
JavaScript面试题1
作用域:
题目1:
var v = 123; function foo() { var v = 456; function inner() { console.log(v) } return inner } result = foo(); console.log(result())
结果:
var v = 123; function foo() { var v = 456; function inner() { console.log(v) } return inner } result = foo(); //456 console.log(result()) //undefined
this的区别:
题目1:
Name = 'root'; Age = 18; //function Foo(){} 函数名大写时一般是类 function Foo(name,age) { this.Name=name; this.Age = age; this.Func = function () { console.log('---',this.Name,this.Age); (function () { console.log(this.Name,this.Age); })() } } obj = new Foo("Alex",666); obj.Func();
结果:
Name = 'root'; Age = 18; //function Foo 函数名大写时一般是类 function Foo(name,age) { this.Name=name; this.Age = age; this.Func = function () { console.log('---',this.Name,this.Age); //Alex 666 (function () { console.log(this.Name,this.Age); //root 18 })() } } obj = new Foo("Alex",666); obj.Func();
题目2:
Name = 'alex'; obj = { Name: 'root', Age: 18, Func: function () { console.log(this); console.log(this.Name); var that = this; function inner() { console.log(this.Name); console.log(that.Name); } inner(); // 自执行函数 (function () { console.log(this.Name) })(); } }; obj.Func()
结果:
Name = 'alex'; obj = { Name: 'root', Age: 18, Func: function () { console.log(this); //this==obj console.log(this.Name); //root var that = this; function inner() { //this = window console.log(this.Name); //alex console.log(that.Name); //root } inner(); // 自执行函数 (function () { console.log(this.Name) //alex })(); } }; obj.Func()