本文最后更新于 2024-03-23T16:32:36+00:00
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| function Person(name,age){ this.name = name; this.age = age; } var person1 = new Person("张三",18); var person2 = Person("李四",12);
console.log(person1); console.log(person2); console.log(person1.name, person1.age); console.log(window.name, window.age);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| function test(arg) { this.x = arg; return this; }
var x = test(5); var y = test(6);
console.log(x.x); console.log(y.x);
var x = test(5); => window.x = window.test(5) window.x = 5; x = window; => window.x == x == window
var y = test(6); => window.y = window.test(6) window.x = 6; y = window; => window.x == x == 6
x.x => 6.x => undefined y.x => window.x => 6
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| var obj = { data: [1, 2, 3, 4, 5], data2: [1, 2, 3, 4, 5], fn: function () { console.log("--test--"); console.log(this); return this.data.map(function (item) { console.log(this); return item * 2; }); }, fn2: function () { console.log("---test2---"); console.log(this); return this.data2.map((item) => { console.log(this); return item * 2; }); }, }; obj.fn(); obj.fn2();
|
4、 this 问题
https://mrhzq.github.io/职业上一二事/前端面试/每日一题/4、 this 问题/