Javascript:为什么复制值而不更改

Javascript : why copy value but not change

本文关键字:为什么 复制 Javascript      更新时间:2023-09-26

我有这个setter,但我不知道为什么要设置值,而且它不会改变:

    this.setHead = function(head){
        console.log('Head: x:'+this.getHead().getX()+' y:'+this.getHead().getY());
        console.log('temp Head: x:'+head.getX()+' y:'+head.getY());
        this.head = head;
        console.log('Head: x:'+this.getHead().getX()+' y:'+this.getHead().getY());
    }

Chrome日志中的结果是:

Head: x:5 y:10 // old value
temp Head: x:1 y:7 //temporary value decide to copy
Head: x:5 y:10     // and the new valụe : NO CHANGE

我读过Javascript通过引用传递对象,我不知道它和Java有什么区别。如果没有,我不知道为什么会发生这种事。请告诉我。

谢谢:)

@编辑:我添加了一行日志,看到奇怪的结果:

console.log('Head: x:'+this.head.getX()+' y:'+this.head.getY());
Head: x:1 y:7 

这很奇怪,因为我认为它应该和下面的线一样,但它不是

console.log('Head:x:'+this.getHead().getX()+'y: '+this.getHead().getY());

我的getHead()是:

this.getHead = function() {
            return head;
}

Javascript不通过引用传递任何内容,设置this.head不会神奇地使head引用其他内容(这就是引用所暗示的)

您的.getHead()方法返回head,而不是this.head,因此赋值根本不会影响getHead()。它们指的是不同的对象。

试试这个:

this.getHead = function() {
    return this.head;
}

基本上你拥有的是最有可能的:

function Ctor( head ) {
    this.getHead = function() {
        return head;
    }
    this.setHead = function( head ) {
        this.head = head;
    }
}

setHead设置对象属性,其中作为getHead返回初始化时传递给构造函数的head变量。

为了避免这种混乱,你应该坚持对象属性和原型,这一切都很简单:

function Ctor( head ) {
    this.head = head;
}
Ctor.prototype.getHead = function() {
    return this.head;
};
Ctor.prototype.setHead = function(head) {
    this.head = head;
};
var o = function(){
  var self = this; // assign 'this' function to a variable
                   // so that it can be accessed in child functions
  var head = {};
  this.getHead = function(){
   ...
   return self.head;
  }
  this.setHead = function(head){
   ...
   self.head = head;
  }
}