[英]javascript correct way to self-reference variables of a function during initialization
The following works and does what I need. 以下工作和做我需要的。 However, is there a better way to reference "a" and "b" in "c:"? 但是,是否有更好的方法在“ c:”中引用“ a”和“ b”?
<html>
<head>
<script type="text/javascript">
var bar;
function Foo() {}
Foo.prototype = {
a: 1,
b: 2,
c: function() {
return Foo.prototype.a + Foo.prototype.b;
}
}
bar = new Foo();
console.log('c is: ' + bar.c());
</script>
</head>
<body>
<button onclick="document.write('c is: ' + bar.c())">Try it</button>
</body>
</html>
c: function() {
return this.a + this.b;
}
When you create a new object of Foo, the properties in the constructor function and the ones added through the prototype can be access, in the objects context scope with the this
word. 当创建Foo的新对象时,可以在带有this
词的对象上下文范围中访问构造函数和通过原型添加的属性。
(function() {
var bar;
function Foo() {
//Constructor function properties and methods
}
//Protoytpe methods and properties
Foo.prototype = {
a: 1,
b: 2,
c: function() {
return this.a + this.b;
}
}
bar = new Foo();
console.log('c is: ' + bar.c());
})();
For more info on how the prototype works, check this out: How does JavaScript .prototype work? 有关原型工作方式的更多信息,请查看以下内容: JavaScript .prototype如何工作?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.