示例1:
<script>
//this指向问题
var name = '222';
var a = {
name: '111',
say: function() {
console.log(this.name); //222
}
}
var fun = a.say;
fun();
a.say(); //111
var b = {
name: '333',
say: function(fun) {
fun(); //this--b
//此时fun()--function() {console.log(this.name);}()
}
}
b.say(a.say); //a.say--function() {console.log(this.name);} 222
b.say = a.say;
b.say(); //333
</script>
示例2:
<script>
var foo = 123;
function print() {
this.foo = 234; //此时这里的this指向window即全局,也就是相当于将原来的123改为了234
console.log(foo);
}
print();
</script>
示例3:
<script>
var foo = 123;
function print() {
//var this = Object.create(print.prototype);
this.foo = 234; //此时this则为Object.create(print.prototype);,并不指向window
console.log(foo); //而结果需要打印的是foo并不是this上的foo,因此则会向上找到,找到var foo=123
}
new print();
</script>
示例4:
<script>
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
</script>
示例5:
<script>
function print() {
var marty = {
name: "marty",
printName: function() {
console.log(this.name);
}
}
var test1 = {
name: "test1"
};
var test2 = {
name: "test2"
};
var test3 = {
name: "test3"
};
test3.printName = marty.printName;
var printName2 = marty.printName.bind({
name: 123
});
marty.printName.call(test1); //test1
marty.printName.call(test2); //test2
marty.printName(); //marty
printName2(); //123
test3.printName(); //test3
}
print();
</script>
示例6:
<script>
var bar = {
a: '123'
};
function print() {
bar.a = 'a';
Object.prototype.b = 'b'; //
return function inner() {
console.log(bar.a); //a
console.log(bar.b); //b
};
}
print()();
</script>