this指向问题 --无return

时间:2024-10-15 13:38:08

this的指向在函数定义的时候是确定不了的只有在函数执行的时候才能确定this到底指向谁。this指向上一级对象

1.函数调用,this指向window

var color = "red"
function test() {
var color = "yellow"
console.log(this.color) //red
console.log(this) //window
}
test()
 var a = 8;
var c = {
a :10,
b:{
a: 12,
fn: function() {
a: 13
console.log(this.a) //
console.log(this) //window
}
}
}
var test = c.b.fn
14      test()

2.构造函数,this指向实例对象

 function user(name, age) {
this.name = name
this.age = age
this.say = function() {
console.log(this.name) //wu
console.log(this) //user{name: 'wu'...}
}
}
var wus = new user('wu', 12)
wus.say()
 function Fn() {
this.name = 'wu'
console.log(this) //Fn
}
var jia = new Fn()
console.log(jia.name) //wu

3.apply,call上下文调用, this指向传入的第一个参数(改变this指向)

 var a = {
name:"wu",
fn:function(){
console.log(this.name); //wu
}
}
var b = a.fn;
b.call(a);
var a = {
name:"wu",
fn:function(){
console.log(this); // window
}
}
var b = a.fn;
b.call(null);
 var a = {
name:"wu",
fn:function(b,c){
console.log(this.name); //wu
console.log(b+c); //12qw
}
}
var d = a.fn;
d.apply(a,[12,"qw"]);

4.方法调用,this指向调用对象

var a = 8;
var c = {
a :10,
b:{
a: 12,
fn: function() {
a: 13
console.log(this.a) //
console.log(this) //b
}
}
}
var test = c.b.fn()
 var color = "red"
var test= {
color :"yellow",
getColor: function() {
console.log(this.color) //yellow
console.log(this) //test
}
}
test.getColor() // === window.test.getColor()
 getColor() // is not defined