无法将具有元素作为原型的 onbject 添加到 dom
考虑这个设置:
function makeObj(a){
this.foo = 'bar';
this.prototype = a;
}
b = makeObj(document.getElementById('foo'));
document.getElementById('bar').appendChild(b);
这会产生一个错误:
节点无法插入到层次结构中的指定点”代码:“3
为什么会这样?对象b
有一个有效的元素作为其原型。不应该起作用吗?
Consider this setup:
function makeObj(a){
this.foo = 'bar';
this.prototype = a;
}
b = makeObj(document.getElementById('foo'));
document.getElementById('bar').appendChild(b);
this gives an error:
Node cannot be inserted at the specified point in the hierarchy" code: "3
Why so? Object b
has a valid element as its prototype. Shouldn't it have worked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有几个问题。
首先
makeObj()
根本没有创建一个新对象。这只是一个函数调用,该函数调用中的 this 可能引用了 window 对象。您必须将makeObj()
与new
运算符一起使用才能实际创建一个新的 javascript 对象。其次,你只能将 DOM 对象附加到 DOM,而不是常规的 javascript 对象。
第三,仅仅将一个 DOM 对象分配给另一个对象的原型并不会让另一个对象突然变成 DOM 对象。如果您想要 DOM 对象,则需要使用
createElement()
或其他记录的创建 DOM 对象的方法之一来创建 DOM 对象。如果您能更多地描述您真正想要实现的目标,我们可以提供进一步的建议。
There are several issues here.
First
makeObj()
isn't making a new object at all. It's just a function call andthis
in that function call is likely referring to thewindow
object. You would have to usemakeObj()
with thenew
operator to actually create a new javascript object.Secondly, you can only append DOM objects to the DOM, not regular javascript objects.
Thirdly, just assigning a DOM object to another object's prototype does not make that other object suddenly become a DOM object. If you want a DOM object, you need to create a DOM object using something like
createElement()
or one of the other documented ways of creating DOM objects.If you can describe more about what you're really trying to accomplish, we could advise further.