原型继承中对象的问题

<script>
    function Parent() {
        this.data={a1:'a1'}
        this.show=function () {
            console.log(this.data)
        }
    }
    function Child(){
        this.set=function () {
            this.data['a2']='a2'   //改变原型中的对象
            this.data='d' //改变当前对象的data,并不能改变 原型上面的 data
        }
    }
    //所有的原型都是指向同一个对象,(引用的同一个对象),改变则所有的改变
    Child.prototype = new Parent()
    var child1 = new  Child()
    var child2 = new  Child()
    child1.set()
    //   this.data['a2']='a2'   //改变原型中的对象,指针的形式
    //   this.data='d' //改变当前对象的data,并不能改变 原型上面的 data
    //   不能改变原型上面的属性值,只能改变原型什么属性对应的应用中的值
    child2.show()
    //   对象中不含this.data,返回原型上面的data,因为指向的是同一个原型,所有打印 {a1:'a1',a2:'a2'}
    console.log('child1',child1)
    console.log('child2',child2)
</script>

  

posted @ 2017-10-20 14:47  小结巴巴吧  阅读(225)  评论(0编辑  收藏  举报