js(引用类型和setTimeout scope)

题目是群中小伙伴出的。

var a = [1,2,3]; c= a
//todo 限制条件 c 不能出现在 = 左边
console.log(a)
console.log(c)
console.log(a === c)


在todo中写段代码 执行
[]
[]
true

我想到的答案

1. a.length = 0

2. 群中其他人的答案  a.splice(0,a.length)

想到的错误办法:

1. a = []  //因为array是引用类型,a = [] ,只是指向一个新的array,c还是指向老的array

2. for(var i = 0 ; i < a.length ; i ++){delete a[i]}  //delete删除了元素,但是没有删除下标 ,会变成[undefined × 3] 这个样子

还可以引申一些问题,例如:

不同变量的区别、引用类型其他的一些问题

ps:还有一个是我原来一直误解的,假使变量a,c都是值引用,原始值a改变的时候,引用的那个c都是不会变的,除非重新赋值……

-----------------------------------------------华丽的分割线------------------------------------------------------

var Obj=function(msg){
    this.msg=msg;
    this.shout=function(){
        alert(this.msg);
    }
    this.waitAndShout=function(){
        setInterval(this.shout, 2000);
        
    }
}
var aa=new Obj("abc");
aa.waitAndShout();

执行的结果是什么,为什么会有这样的结果呢?

的execution context是在window物件,所以在shout()裡面使用this時,這個this還是指向window物件

详细见: http://fillano.blog.ithome.com.tw/post/257/19165

原文地址:https://www.cnblogs.com/della/p/3559721.html