2014-02-08 2 views
-2
function test() 
{ 
    this.lol = []; 
} 

test.hello = function() 
{ 
    this.lol.push("hello world"); 
} 

test.hello(); 

console.log(test.lol); 

Просто тестовый класс, дает мне следующее:Неопределенный массив в классе?

^ 
TypeError: Cannot call method 'push' of undefined 

Что я делаю неправильно?

+0

Когда, как вы думаете, ваш 'тест()' называется (тот, который создает пустой массив в 'lol' поле)? –

+0

«Что такое« это »- один из самых сложных вопросов в мире js. Взгляните на 'this' :) http://www.quirksmode.org/js/this.html – lucke84

ответ

1

если вы waant сделать это, вы должны сделать это нравится:

function Test() { 
    this.lol = []; 
} 

Test.prototype.hello = function() { 
    this.lol.push("hello world"); 
} 
var test = new Test(); 
test.hello(); 
console.log(test.lol); 

точка, когда вы используете this клавиатуры, вы должны использовать его в качестве Class или вы должны обеспечить this для контекста использования call или apply, как:

function testFunc() { 
    this.lol = []; 
} 

testFunc.hello = function() { 
    this.lol.push("hello world"); 
} 

var test = {}; 

//this way you call the testFunc with test as its `this` 
testFunc.call(test); 

//this calls the testFunc.hello with the same `this` 
testFunc.hello.call(test); 

console.log(test.lol); 
Смежные вопросы