个人总结:https://github.com/Tom-cy/Immortals 欢迎Star 持续更新
简单的介绍下什么是对象 :
- 只要是对象就有自己的私有属性
- 只要是new出来的都是对象
- 不同的对象肯定不相等
- 对象都会有引用机制,如果不想引用就重新赋值
这四点是我总结出来的,可能不是很全面,毕竟我也是才刚刚入门!
this指向问题
- 在普通函数下this指向的我window
- 有事件源指向事件源
- 全局作用域this:在定时器下除es6,this指向window
- 在对象下this指向的是自己本身
这四点是我总结出来的,可能不是很全面,毕竟我也是才刚刚入门!
接下来是一些小小的测试题,难度不是很深,我会把答案放在下一题中,有的答案也可以直接输出的:
this-指向:
举例 1:
<script>
var num = 10;
var obj = {
num: 8,
inner: {
num: 6,
print: function () {
console.log("num: " + num + " , this.num: " + this.num);
}
}
}
num = 888;
// 第一次执行
obj.inner.print();
// 第二次执行
var fn = obj.inner.print;
fn();
// 第三次执行
(obj.inner.print)();
// 第四次执行
(obj.inner.print = obj.inner.print)();
</script>
举例2:
<script>
var foo=123;
function print(){
this.foo=789;
console.log(foo);
}
print();
new print();
</script>
举例1:答案:
// num: 888 , this.num: 6
// num: 888 , this.num: 888, this: Window
// num: 888 , this.num: 6
// num: 888 , this.num: 888 , this: Window
举例3:
<script>
var a=5;
function test(){
a=0;
alert(a);
alert(this.a);
var a;
alert(a);
}
test();
new test();
</script>
举例2 答案:
// 执行print函数,函数里面没有foo,查看全局,foo=123,但print里面的this指向是window,
// 将123改为789了,所以得到的是789
print();
// 执行了一个新的print的函数,相当于在函数内部var this=object。create(print.prototype),
// 此时this指向是函数内部了,不会改变123,所以得到的是123
new print();
举例4:压轴题:答案自己console.log,
<script>
var name = "222";
var a = {
name: "111",
say: function () {
console.log(this.name);
}
}
var fun = a.say;
fun();
a.say();
var b = {
name: "333",
say: function (fun) {
fun();
}
}
b.say = a.say;
b.say(a.say);
b.say();
举例3 答案:
<script>
var a=5;
function test(){
// var this=object.create() 隐式执行 new出来的 没有a 返回undefined
a=0;
alert(a);
alert(this.a);
var a;
alert(a);
}
// 0,5,0
test();
// 0,undefined,0
new test();
</script>
</script>