[英]Calling property from an object set to prototype
var Foo = function() {
this.message = "Hi";
}
Foo.prototype = {
say: {
hi: function() {
console.log(this.message);
}
}
}
[edit]I know "this" in hi() refers say, is there any way to achieve this? [edit]我知道hi()中的“ this”是指说,有什么方法可以实现?
var he = new Foo();
he.say.hi(); //"Hi" to console
You can access like this. 您可以像这样访问。
var Foo = function(){
this.par = 3;
this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
this.p = t;
this.subFunction = function(){
alert(this.p.par);
}
})(this);
}
var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;
myObj.par = 5;
myObj.sub.subFunction()
All you need is to bind the hi function just like this: 您所需要做的就是绑定hi函数,如下所示:
var Foo = function() {
this.message = "Hi";
this.say.hi = this.say.hi.bind(this);
}
Foo.prototype = {
say: {
hi: function() {
console.log(this.message);
}
}
}
var he = new Foo();
he.say.hi();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.