【发布时间】:2016-04-17 08:51:49
【问题描述】:
我是 javascript 新手,正在努力解决以下问题。
让我们考虑一下这种情况。
首先,有一个像这样的对象。
var bar = {
'name' : 'bob',
'comments' : []
}
但是由于某些原因,我们只有一个名为 'foo' 的变量,这与 bar.comments 完全相同。
其次,因为我们需要引用对象bar,所以foo中必须存在方法,命名为callParent。如果我们满足所有这些条件,我们可以使用foo.callParent() 获取对象bar。
要像上面那样实现,首先,我定义了一个构造函数名称Custom。
function Custom(param){
this.callParent = function(){
console.log(param);
}
}
然后,要像数组一样使用Custom 的实例,继承数组。
Custom.prototype = Array.prototype;
之后,我想定义对象bar,如下所示。
var bar = {
'name':'bob',
'comments':new Custom(this)
}
在那个实现中,因为我认为this 本身就是bar,所以我预计结果foo.callParent() 将是bar,但它是window。我认为这是因为在调用foo.callParent() 的上下文中,this 不再意味着bar。
最后,我这样解决这个问题。
var bar = {
'name':'bob',
'comments':undefined,
'init':function(){
this.comments = new Custom(this);
return this;
}
}.init();
Qeustion:有没有什么办法可以在不借助bar.init等其他方法的情况下解决这种情况?我只想通过更改构造函数Custom 来解决这个问题!和IIFE有关系吗?
【问题讨论】:
-
喜欢这个?
var bar = { 'name':'bob', 'comments':new Custom(bar) } -
@tresden 这不起作用 - 将通过
undefined。 -
@DanielA.White 哦,我的错。它应该与您的答案相似。
标签: javascript constructor prototype this iife