JavaScript

问题:对引用型变量覆盖赋值后,其内存过程是如何的?
由下面的程序可以推断,应该是销毁原先的的内存区域,在新的内存中重新创建同名变量,因为其内存地址是不同的...

程序说明:在原型中查找值的过程是一次搜索,对原型对象的任何修改都能立刻从实例上反映出来,即使是先创建了实例后再修改原型也照样如此。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>this is an example</title>
</head>
<body>
        
    <script type="text/javascript">
        // 建立构造函数
        function Animal(name,age,color){
            this.name = name;
            this.age = age;
            this.color = color;
        }
        // 由构造函数创建实例
        var cat = new Animal("cat",3,"black");
        // 为原型对象添加 sayHi 函数
        Animal.prototype.sayHi = function(){
            alert("Hi ");
        }
        //重写原型对象
        Animal.prototype = {
                 constructor : Animal,
                type : "eatMeat",
                run : function(){
                    alert("i can run fast");
                }    
        }
        
        alert(Animal.prototype.isPrototypeOf(cat));// false
        
        cat.sayHi();// 调用原型的 sayHi 函数  正常
        //cat.run();// 调用原型的run 函数  错误
        
        // 原型对象重写后,由构造函数创建的实例指针无法指到新的原型对象
        /*  
            问题:
                对引用型变量覆盖赋值后,其内存过程是如何的?
                
                由上面的例子可以推断,应该是销毁原先的的内存区域,在新的内存中重新创建同名变量
        
        */
        
        Table = {
                name : "godd",
                age : 8,
                sayHi : function(){
                    alert("Hi table ");
                }
        }
    
        Table.sayHi();
        
        Table = {
                color : "red",
                sayHello : function(){
                    alert("hello");
                }
        }
      //Table.sayHi(); //error!
         Table.sayHello();
      
    </script>   
</body>

也就是说,新Table 和原先的Table 在内存中的地址应该是不一致的,整个过程应该是先销毁原先的 Table,然后在内存中重新建 新的Table

原文地址:https://www.cnblogs.com/zhanghust/p/5936565.html