我在下面遇到了JavaScript(ES6)的问题
class A{
constructor(){
this.foo();
}
foo(){
console.log("foo in A is called");
}
}
class B extends A{
constructor(){
super();
this.foo();
}
foo(){
console.log("foo in B is called");
}
}
Run Code Online (Sandbox Code Playgroud)
我期待的是
foo in A is called
foo in B is called
Run Code Online (Sandbox Code Playgroud)
但事实上确实如此
foo in B is called
foo in B is called
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过简单地添加super.foo()B类的foo函数来解决这个问题
class B extends A{
constructor(){
super();
this.foo();
}
foo(){
super.foo() // add this line
console.log("foo in B is called");
}
}
Run Code Online (Sandbox Code Playgroud)
但想象一下类似的情景:
Child必须覆盖父项的功能才能执行一些额外的工作,并阻止外部访问能够访问原始功能.
class B …Run Code Online (Sandbox Code Playgroud) <html>
<head>
<title>test</title>
<script type="text/javascript">
function start(){
document.getElementById("first_div").onclick = function(){
document.getElementById("another_div").style.color = "red";
};
}
</script>
</head>
<body onload="start()">
<div id="first_div">first</div>
<div id="anoter_div">second</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我点击first_div时,发生了一个错误:
TypeError: Result of expression 'document.getElementById("another_div")' [null] is not an object.
Run Code Online (Sandbox Code Playgroud)
知道为什么这不起作用吗?
谢谢.