js中this的指向
2021-04-16 02:40
标签:ret turn 赋值 var his 调用 实例 函数 包含 js中this的指向 标签:ret turn 赋值 var his 调用 实例 函数 包含 原文地址:https://www.cnblogs.com/fm060/p/12305818.html//被上级调用,上级为window
function a(){
var user = "追梦子";
console.log(this.user); //undefined
console.log(this); //Window
}
a();
//被上级调用,上级为window
function a(){
var user = "追梦子";
console.log(this.user); //undefined
console.log(this); //Window
}
window.a();
//被上级调用,上级有user
var o = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
o.fn();
// 只寻找上一级,上级为o
var o = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
window.o.fn();
// 只寻找上一级,上级为b
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();
//上级为b,调用时b中没有a
var o = {
a:10,
b:{
// a:12,
fn:function(){
console.log(this.a); //undefined
}
}
}
o.b.fn();
//赋值时没有调用,this为window
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
function Fn(){
this.user = "追梦子";
}
var a = new Fn();
console.log(a.user); //追梦子
function fn()
{
this.user = ‘追梦子‘;
return {};
}
var a = new fn;
console.log(a.user); //undefined
function fn()
{
this.user = ‘追梦子‘;
return undefined;
}
var a = new fn;
console.log(a); //fn {user: "追梦子"}