从对象内部的对象内部访问实例变量

时间:2019-01-14 00:23:24

标签: javascript javascript-objects

var MyObj = function(x) {
   this.x = x;
   this.y = 5;
};

MyObj.prototype.example = function() {
   // I want to return a new object which has access to this.x and this.y

   // For example:
   return {
      addTwo: function() {
         // How can I access this.x from the MyObj instance?
         return 2 + (x from the instance of MyObj)
      }
   }
};

如何从示例方法返回对象,以便它可以访问MyObj实例的实例变量?

我不能在返回的对象内使用“ this”,否则它将引用我要返回的对象。

我没有使用es6

3 个答案:

答案 0 :(得分:2)

有几个选项-最简单的方法是创建对this实例的MyObj的引用,并在对象{{1 }}这样返回:

addTwo()

答案 1 :(得分:2)

您没有说明是否可以使用es6。基本上,这是范围问题。使用es6和babel,您可以执行

之类的操作

ES6方法

      body {
  margin: 0;
  padding: 0;
  background: #333;
  background-attachment: fixed;
  background-size: cover;
}

#video-background {
  position: fixed;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  z-index: -100;
}

article {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 10px solid rgba(255, 255, 255, 0.5);
  margin: 10px;
}

h1 {
  position: absolute;
  top: 60%;
  width: 100%;
  font-size: 36px;
  letter-spacing: 3px;
  color: #fff;
  font-family: Oswald, sans-serif;
  text-align: center;
}

h1 span {
  font-family: sans-serif;
  letter-spacing: 0;
  font-weight: 300;
  font-size: 16px;
  line-height: 24px;
}

h1 span a {
  color: #fff;
}

通过这种方式,<!DOCTYPE html> <html> <body> <link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'> <video autoplay loop id="video-background" plays-inline> <source src="video.mp4" type="video/mp4"> </video> </body> </html>不会改变,因为箭头函数具有从外部范围继承的var MyObj = function(x) { this.x = x; this.y = 5; }; MyObj.prototype.example = function() { // I want to return a new object which has access to this.x and this.y // For example: return { addTwo: () => { // How can I access this.x from the MyObj instance? return 2 + this.x } } }; 上下文。

供参考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

基本上可以转换为类似的东西(您没有使用类,所以我假设您没有使用es6)

旧方法

this

它将只是将this变量“存储”到其他变量以供以后使用(这就是babel在后台进行的类似操作)。

.bind()方法

如果您想第3个答案,可以这样将var MyObj = function(x) { this.x = x; this.y = 5; }; MyObj.prototype.example = function() { // I want to return a new object which has access to this.x and this.y var that = this // For example: return { addTwo: function(){ // How can I access this.x from the MyObj instance? return 2 + that.x } } }; 上下文绑定到被调用的函数

this

它将“转移” this到该功能。

供参考 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

答案 2 :(得分:0)

如果使用箭头功能,this上下文在内部将不会更改:

var MyObj = function(x) {
   this.x = x;
   this.y = 5;
};

MyObj.prototype.example = function() {
   return {
      addTwo: () => 2 + this.x
   }
};

const o = new MyObj(2);
console.log(o.example().addTwo());

相关问题