1

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

    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('头:x:'+this.getHead().getX()+'y:'+this.getHead().getY());

getHead()的是:

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

2 回答 2

3

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

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

尝试这个:

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

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

function Ctor( head ) {

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

    this.setHead = function( head ) {
        this.head = head;
    }

}

setHeadset 对象属性,其中 asgetHead返回head初始化时传递给构造函数的变量。

为了避免这种混淆,您应该只使用对象属性和原型,这一切都非常简单:

function Ctor( head ) {
    this.head = head;
}

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

Ctor.prototype.setHead = function(head) {
    this.head = head;
};
于 2012-08-01T16:47:40.000 回答
1
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;
  }
}
于 2012-08-01T16:39:59.123 回答