Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

既然函数也是引用类型,为什么原型继承无法改变

如题,下面代码里数组可以改变,但是函数却无法改变:

        var human = {
            say:function(){
               console.log("我是人类");
            },
            arr:[1,2,5,4]
         }
         
         human.say();

             
             var people = Object.create(human);
             
             people.say = function(){
                console.log("我改变了他");
             }
             people.arr.push("hello");
             
             people.say();    //输出的是"我改变了他"

             var anotherPeople = Object.create(human);   
             
             anotherPeople.say();    //没有变化,还是"我是人类"
             
             console.log(anotherPeople.arr);   //数组arr =[1,2,5,4,'hello']
             
             

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你这个问题就好比:
var a = {data:1};
var b=a;
b={data:3};

console.log(a);//{data:1}

var a = {data:1};
var b=a;
b.data=3;
console.log(a);//{data:3}

你得分清楚操作对象和改变变量的指向。。。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...