2017-06-29 190 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())