【问题标题】:accessing siblings in javascript [closed]在javascript中访问兄弟姐妹[关闭]
【发布时间】:2012-05-10 03:14:12
【问题描述】:

我正在编写一个节点应用程序,我想获取调用构造函数的变量的名称。

a=new constructorFunction();
b=new constructorFunction();

function constructorFunction(){
    this.test="it works!";
    this.doSomething=function(){
       //this should return the contents of this.test
    }
}

console.log(a.doSomething());
console.log(b.doSomething());

正如评论所说,我想返回 a.test 和 b.test 的值。我怎样才能做到这一点?

【问题讨论】:

  • 当我在 this.doSomething() 中的 console.log(this.test) 中返回 undefined。
  • 那么你发布的代码和你的代码不匹配。
  • bennadel.com/blog/… - 所以在定义时,thisconstructorFunction
  • 但是在doSomething的定义中,有一个return this.test; ??如果不是,那么这就是你的答案!
  • 错了。我过度简化了我的代码来做一个例子,并错过了一个明显的错误。

标签: javascript oop node.js


【解决方案1】:

不需要比这更复杂(fiddle):

function constructorFunction() {
  this.test="it works!";
  this.doSomething = function() {
    return this.test;
  }
}

【讨论】:

  • 如果doSomethingconstructorFunction.prototype 上,我会投赞成票。
【解决方案2】:
a=new constructorFunction();
b=new constructorFunction();

function constructorFunction(){
    var self = this;
    this.test="it works!";
    this.doSomething=function(){
       return self.test;
    }
}

【讨论】:

    【解决方案3】:

    在 chrome 中这有效...(V8 所以我假设 node.js 的行为相同)

    http://jsfiddle.net/zTTZR/1/

    a=new constructorFunction();
    b=new constructorFunction();
    
    function constructorFunction(){
        this.test="it works!";
        this.doSomething=function(){
           return this.test;
        }
    }
    
    console.log(a.doSomething());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 2011-05-01
      • 2019-08-04
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多