this问题
this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
出自: 追梦子博客
例子1:
function a(){
var user = "追梦子";
console.log(this.user); //undefined
console.log(this); //Window
}
a();
例子2:
var o = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
o.fn();
例子3:
var o = {
user:"追梦子",
fn:function(){
console.log(this.user); //追梦子
}
}
window.o.fn();
例子4:
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();
例子5:
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
例子6:
function Fn(){
this.user = "追梦子";
}
var a = new Fn();
console.log(a.user); //追梦子
call,apply,bind问题
来自: 追梦子博客
js经典问题
来自: 小小沧海
function Foo() {
getName = function () { console.log(1); };
console.log(this)
return this;
}
Foo.getName = function () { console.log(2);};
Foo.prototype.getName = function () { console.log(3);};
var getName = function () { console.log(4);};
function getName() { console.log(5);}
Foo.getName();//2
getName();//4
Foo().getName();//1
getName();//1
new Foo.getName();//2
new Foo().getName();//3
new new Foo().getName();//3
自己整理的直接贴答案
var a = 10;
sayHi();
function sayHi(){
a = a+ 10;
console.log(a);
return a;
}
console.log(a);
console.log(sayHi() + 10)
// 20 20 30 40
var a = 10;
sayHi();
function sayHi(){
var a = a+10;
console.log(a)
return a;
}
console.log(a);
console.log(sayHi() + 10)
// NaN 10 nan nan
var length = 10;
function fn(){
console.log(this.length)
}
var obj = {
length: 5,
method: function(fn){
fn()
console.log(this.length)
}
}
obj.method(fn)
// 10 5
var uname = 'jack';
function change(){
console.log(uname);
var uname = 'lily';
console.log(uname)
}
change()
// undefined lily
这有两个不是很理解的问题,放在这里做个记录(下面的解释是别人说的,当做参考)
问题1:
var a = 5;
function test() {
a = 0;
console.log(a);
console.log(this.a);
var a;
console.log(a);
}
test();//0 5 0
new test();//0 undefined 0
运行test(),this指向window对象。所以首先test函数声明了一个变量a并赋值0,这个变量和全局变量a是不干扰的。所以第一个alert(a)输出0,接下来alert(this.a),this指向window对象,所以输出全局对象下的变量a(5),最后一个alert与第一个实际上是一样的,所以还是0。
理解了上面的话下面的问题就是为什么执行new test()时第二个弹出的是undefined。当执行new test()时,相当于是实例了一个test对象,这时候this指向的是这个实例。但是这个实例并没有定义属性a,所以alert(this.a)时会是undefined。
问题2:
var a = "111";
var b = "222";
function test() {
var a = "333";
var b = "444";
console.log(this.a);
console.log(this.b);
}
var test = new test();
console.log(test.a);
console.log(test.b);
//undefined undefined undefined undefined
因为使用new来声明函数,创建了一个test() 对象test,所以函数体内的this指针指向test,由于test并没有定义a,b的值,返回undefined。
问题3:这个问题不太懂,也没看到解释
function a(xx) {
this.x = xx;
return this;
}
var x = a(5);
var y = a(6);
console.log(x.x); //undefined
console.log(y.x); //6