关于JS函数中的原型到底是怎么回事。引用类型的原型变量,存储过程到底是怎么样的。

<script type="text/javascript">
        function Person(name, age, gender) {
            this.name = name;
            this.gender = gender;
            this.age = age;
        }
        Person.prototype.sayHi = function(){
            alert('我是' + this.name + '今年' + this.age + '我是' + this.gender + '生');
        }
        var wmm = new Person('王明明', 18, '女');
        wmm.sayHi();
        //prototype的只读属性问题
        //在prototype中设置的值变量是只读的
        Person.prototype.class = '鸳鸯二班';
        Person.prototype.school = '北京小学';
        Person.prototype.friends = ['王大力', '李小璐', '蔡明明'];

        var wlc = new Person('旺理财', 5, '男');
        wlc.class = '法拉利班';

        alert(wlc.class);
        var lct = new Person('理财添', 2, '女');
        alert(lct.class);//可以发现,class属性并没有改变
        lct.friends[0] = '我是谁';//对于引用类型的变量
        lct.friends[1] = '我在哪';//如果通过栈中的地址码找到对应堆中的字段,可以将其改变
        alert(lct.friends);
        alert(wlc.friends);
        //如果只是修改引用类型的地址码本身,是不让修改的,而是创建了一个新的属性,隐藏了原型中的变量
        lct.friends = ['再看看', '谁变了', '谁没变'];
        alert(lct.friends);
        alert(wlc.friends);

    </script>
发布了55 篇原创文章 · 获赞 4 · 访问量 1401

猜你喜欢

转载自blog.csdn.net/BowenXu11/article/details/105227066