我通常不是一个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更改为我班级中的函数,然后从那里处理它。
任何帮助都将不胜感激。
答案 0 :(得分:1)
如何将DoMathResponse作为回调函数传递
Eg)的
function ChildClass(){
this.X;
this.Y;
this.DoMath = function(onComplete) {
var answer = this.X + this.Y;
onComplete (answer);
};
}
$(document).ready(function(){
var cClass = new ChildClass();
cClass.X = 8;
cClass.Y = 5;
var DoMathResponse = function(answer){
alert(answer);
};
var DoMathRequest = function(){
cClass.DoMath(DoMathResponse);
};
答案 1 :(得分:0)
而不是声明:
cClass = new ChildClass();
你应该尝试:
var
这样就可以使变量在类/函数之外全局可用,而不是本地{{1}}声明的变量。