2010-06-11 46 views
2

我在Javascript中有一個簡單的對象。爲什麼我的原型函數不返回實例的屬性?

函數MyClass的(X,Y){

this.x = x; 

this.y = y; 

}

和原型函數

myClass.prototype.myfunction =函數(){

console.log(this.x);

}

在我的主腳本,

變種X = 2; var y = 4;

myinstance = new myClass(x,y);

myinstance.myfunction();

不是接收x,而是取而代之。這是爲什麼?

回答

1

您未使用new運算符,myinstanceundefined

var x = 2; var y = 4; 

myinstance = new myClass(x,y); 
myinstance.myfunction(); // will show `2` in the console 

編輯:既然你說你正在使用的new運營商,我想你可能會在控制檯上執行myinstance.myfunction();,你可能該方法,這是在看結果(返回值)實際上undefined,因爲它不包含return語句。

查看工作示例here

+0

修正 - 我用我的實際代碼的新的運營商。抱歉錯過了這一點。仍然遇到同樣的問題。 – 2010-06-11 07:36:38

+0

@Pydroid:檢查我的編輯和我發佈的示例。 – CMS 2010-06-11 08:05:58

0

我認爲你應該做myinstance = new myClass(x,y);

2

你忘了new關鍵字:

myinstance = new myClass(x,y); 

我嘗試了代碼,並與另外它的工作原理。

0

嗯......試圖實例化這樣

var myClass = function (x,y) {

this.x = x; 
this.y = y; 
this.myfunction = function(){ 
    console.log(this.x); 
} 

}

你的函數這個工作很細,我

相關問題