2017-06-29 135 views
0

如何扩展此范围以便下面的工作?我试过使用.bind()函数,但我似乎无法得到任何工作。如何扩展此范围

var myObj = { 
    test: "Hello", 
    test2: " World", 
    run: { 
     all: function() { 
     return this.test + this.test2; 
     }, 
     part: function() { 
     return this.test2; 
     } 
    } 
} 
console.log(myObj.run.all()) 
// => "Hello World" 
console.log(myObj.run.part()) 
// => " World" 
+0

你必须明白:'this'在你的职责是当前对象,这就是你要的影响'run',而不是超对象。在run(和'this' btw)中,只有'all()'和'part()',没有'test'和'test2'。 – sjahan

回答

0

最近我遇到了同样的问题。 我用一个函数

var myObj = function(){ 
    var self = this; 
    this.test = "Hello"; 
    this.test2 = " World"; 
    this.run = { 
     all: function() { 
     return self.test + self.test2; 
     }, 
     part: function() { 
     return self.test2; 
     } 
    } 
} 
console.log(myObj.run.all()) 
// => "Hello World" 
console.log(myObj.run.part()) 
// => " World" 

解决我也发现了绑定没有工作!

var myObj = { 
    test: "Hello", 
    test2: " World", 
    run: { 
     all: function() { 
     return this.test + this.test2; 
     }, 
     part: function() { 
     return this.test2; 
     } 
    } 
}; 

console.log(myObj.run.all.bind(myObj)()); 
// => "Hello World" 
console.log(myObj.run.part.bind(myObj)()); 
// => "World" 

工作拨弄==>https://jsfiddle.net/sn5w7872/

0

使用apply

apply()方法调用与给定值this的函数和参数作为数组

var myObj = { 
 
    test: "Hello", 
 
    test2: " World", 
 
    run: { 
 
     all: function() { 
 
     return this.test + this.test2; 
 
     }, 
 
     part: function() { 
 
     return this.test2; 
 
     } 
 
    } 
 
} 
 
console.log(myObj.run.all.apply(myObj,[])); 
 
// => "Hello World" 
 
console.log(myObj.run.part.apply(myObj,[]));
提供

-1

使用ES6类和箭头函数。

class myObj { 
    constructor() { 
     this.test = "Hello"; 
     this.test2 = " World"; 
     this.run = { 
      all:() => this.test + this.test2, 
      part:() => this.test2 
     } 
    } 
} 

var obj = new myObj(); 
console.log(obj.run.all()) 
// => "Hello World" 
console.log(obj.run.part()) 
// => " World" 

这里是工作提琴 - https://jsfiddle.net/sgsvenkatesh/vn9b1f95/

1

功能allpart是对象的成员runrun没有价值testtest2。他们是myObj的成员对象。

您可以用myObj替换this关键字。

var myObj = { 
 
    test: "Hello", 
 
    test2: " World", 
 
    run: { 
 
     all: function() { 
 
     return myObj.test + myObj.test2; 
 
     }, 
 
     part: function() { 
 
     return myObj.test2; 
 
     } 
 
    } 
 
} 
 
console.log(myObj.run.all()) 
 
console.log(myObj.run.part())