2017-07-26 115 views
0

我非常新的JavaScript 请纠正我的代码或建议最好选择JavaScript变量对象

var myApp = {}; 

myApp.set = function(VAL) { 
    myApp.id = VAL;  
} 

myApp.get = function() { 
    return myApp.id; 
} 

function PageLoad() { 
    var X = new myApp; 
    var Y = new myApp; 

    Y.set(20); 
    X.set(10); 

    alert(X.get()); 
    alert(Y.get()); 
} 

马诺

它表明最后配置值只有10,即:(

在此先感谢

+4

你确定这是你的代码,因为我得到的错误'未捕获的TypeError:myApp不是一个构造函数。 – George

+0

我想有一个错字,应该是'var X = new myApp()'(括号) –

+0

这不能是你的实际代码,因为这段代码没有运行。请向我们显示您的实际代码,否则此问题需要被视为无效。 – jfriend00

回答

1

@Manoj Chavanke先生请使用此代码

function myApp(){ 
    } 
    myApp.prototype.set = function(VAL) { 
     this.id = VAL;  
    } 

    myApp.prototype.get = function() { 
     return this.id; 
    } 

    function PageLoad() { 
     var X = new myApp; console.log(X); 
     var Y = new myApp; console.log(Y); 

     Y.set(20); 
     X.set(10); 

     alert(X.get()); 
     alert(Y.get()); 
    } 
    PageLoad(); 
+0

非常感谢Karan, 你能帮我写相同的代码吗?使用Object Literal Notation? –

0

我想你重写myApp.id = VAL;

试试这个代码

var myApp = []; 
 
myApp.set = function(VAL) { 
 
    myApp.push({id : VAL}); 
 
}
instate的

var myApp = {}; 
 

 
myApp.set = function(VAL) { 
 
    myApp.id = VAL;  
 
}

因为关键是独特的你不能使用两次。