我通常不是JavaScript的人,所以這對我來說有點陌生。在主腳本中創建一個JavaScript類函數調用函數
我試圖做一個JavaScript類,可以在主腳本中調用函數。這裏有一個例子:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
function ChildClass(){
this.X;
this.Y;
this.DoMath = function(){
var answer = this.X + this.Y;
// I'm trying to pass the answer variable back to the "DoMathResponse" function. Currently, the "DoMathRequest"
// is passed to another domain via CDM, processed, then the response is routed back to the "DoMathResponse" function.
// This class is intended to replace the CDM call with as little modification to the existing code as possible, so I
// can't simply return the answer variable.
pClass.DoMathResponse(answer); //<-- I want to do something like this
};
}
$(document).ready(function(){
var cClass = new ChildClass();
cClass.X = 8;
cClass.Y = 5;
var DoMathRequest = function(){
cClass.DoMath();
};
var DoMathResponse = function(answer){
alert(answer);
};
// Button Click Event Handler
$("#btn").click(function(){DoMathRequest();});
});
</script>
</head>
<body>
<div id="btn">Click Me</div>
</body>
</html>
這是可能與JavaScript?現有代碼使用CDM調用另一個域,並試圖用類替換跨域調用。我想通過儘可能少地修改原始代碼來完成此操作。我完全控制了ChildClass,但其他人使用現有的代碼,所以我想調用與跨域消息路由到的功能相同的功能。這樣,我們只需要將CDM下降到我班的功能,然後從那裏處理。
任何幫助,將不勝感激。
點擊事件可以被簡化,從'。點擊(函數(){DoMathRequest();});'來'.click(DoMathRequest)' – evolutionxbox
另外,javascript是一種免費的語言,有類似語法的愚蠢「類」。 – evolutionxbox
@evolutionxbox類在ES6中添加:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class – Rotareti