我正在寻找满足以下要求的JavaScript实现:
我目前对此源代码的问题:一次 Parent 被调用,而不是 Child 。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JS test</title>
<script type="text/javascript">
function write(msg) {
var t = document.createTextNode(msg);
var li = document.createElement("li");
li.appendChild(t);
document.querySelector("ul").appendChild(li);
}
var Parent = function () {
var running = 0;
var run = function () {
running = Infinity;
invokeNextIter();
};
var next = function () {
running = 1;
invokeNextIter();
};
var invokeNextIter = function () {
if (running > 0) {
running -= 1;
setTimeout(function () { once(invokeNextIter); }, 1);
}
};
var once = function (done) {
var time = Math.random() * 3 + 1;
write(time + " sec");
setTimeout(done, time * 1000);
};
return {
run: run,
once: once
};
};
var Child = function () {
var once = function (done) {
write("2 sec as always");
setTimeout(done, 2000);
};
var p = new Parent();
return Object.create(p, { once : once });
};
function main() {
var c = new Child();
c.run();
}
</script>
</head>
<body onload="main()">
<ul>
</ul>
</body>
</html>
无法使用Function.prototype.bind或相关技术运行此功能。任何帮助感激不尽
答案 0 :(得分:1)
好的,在您的情况下,div.col-lg-12(ui-view="")
和Parent
之间唯一不同的功能是 once()功能。
因此,您必须从Child
类开始构建核心,然后将实例方法添加到Parent
和Parent
,以覆盖child
函数。
我们将使用原型继承。规则是您可以使用once()
关键字初始化的任何对象的原型,包括本机javascript对象。
new
在这里,您可以看到 function write(msg) {
var t = document.createTextNode(msg);
var li = document.createElement("li");
li.appendChild(t);
document.querySelector("ul").appendChild(li);
}
var Parent = function(){
//Retrieve context
var self = this;
var running = 0
//Create a `run` function which will refer to the current context
self.run = function(){
running = Infinity;
invokeNextIter();
}
//Declare our private function
var next = function () {
running = 1;
invokeNextIter();
};
var invokeNextIter = function () {
if (running > 0) {
running -= 1;
setTimeout(function () {
//Call once method which is in the prototype of the current context
self.once(invokeNextIter);
}, 1);
}
};
}
//Add a "once" instance method to Parent
Parent.prototype.once = function(done){
var time = Math.random() * 3 + 1;
write(time + " sec");
setTimeout(function(){
done();
}, time * 1000);
}
//Create our Child 'class'
var Child = function(){
}
//Declare Child as a subclass of the first
Child.prototype = new Parent();
//Add a "once" instance method to Child and override the "once" parent method
Child.prototype.once = function(done){
write("1.5 sec as always");
setTimeout(function(){
done();
}, 1500);
}
function main(){
// Create instances and see the overridden behavior
var c = new Child();
var p = new Parent();
//c.run() will call child once() method
c.run();
//p.run() will call parent once() method
p.run();
}
和self.run()
。 self.once()
变量将引用当前实例。