首页 > 技术文章 > js面试题

wenghao 2019-08-27 16:25 原文


var v = 123;
function foo(){
var v = 456;
function inner(){
console.log(v)
}
return inner
}

result = foo()
console.log(result())

# 问输出结果:NULL

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(){
console.log(this.Name,this.Age);
})();
}
}
obj = new Foo('alex',666);
obj.Func()
# 问输出结果:
alex 666
root 18






1. js面向对象

function Func(name,age){
this.Name = name;
this.Age = age;
}
obj = new Func('root',18)

2. this关键字
# 每个函数中都有this
# 函数调用时,this=window
# 类new时, this=obj

function func(){
# 当做函数执行函数时,this=window
console.log(this);
}
func()


function Func(){
# his=obj
console.log(this);
}
obj = new Func()


3. js中无字典,只有对象

Name = 'alex'
obj = {
Name: 'root',
Age: 18,
Func: function(){
# this=obj
console.log(this.Name) # root

function inner(){
# this=window
console.log(this.Name)#alex
}
inner()#函数的调用方式window
}
}
相当于new了对象 obj

obj.Func()就等于obj



Name = 'alex'
obj = {
Name: 'root',
Age: 18,
Func: function(){
# this=obj
console.log(this.Name) # root
var that =this;#修改的地方,那么that这时也是obj
function inner(){
# 这里面this=window
console.log(that.Name)这里的that等于obj
}
inner()
// 子执行函数
(function(){
console.log(that.Name)
})()
}
}
相当于new了对象 obj

obj.Func()













推荐阅读