admin管理员组文章数量:1395785
Here is an object:
var obj = new function(){
this.prop = {};
}
and I try to do something like:
obj.prop.prototype["new_attr"] = "some_value";
What I'd like to do, is permanently modify obj.prop
to contain the new attributes. From what I understood, all "Objects" had the prototype, but JavaScript is telling me prop
doesn't have prototype.
Maybe I'm taking the wrong approach (in trying to permanently modify prop
), but I'd at least like to know why the code above doesn't work.
Here is an object:
var obj = new function(){
this.prop = {};
}
and I try to do something like:
obj.prop.prototype["new_attr"] = "some_value";
What I'd like to do, is permanently modify obj.prop
to contain the new attributes. From what I understood, all "Objects" had the prototype, but JavaScript is telling me prop
doesn't have prototype.
Maybe I'm taking the wrong approach (in trying to permanently modify prop
), but I'd at least like to know why the code above doesn't work.
3 Answers
Reset to default 6Typically you access the prototype
object from the constructor function, but you can get it from an object as well, but not using .prototype
.
The unofficial way (not supported in all browsers) to get the prototype object of an object is with the __proto__
property. (I believe it is deprecated in the browsers that support(ed) it).
The official ECMAScript 5 way (also not supported in all browsers) to get the prototype object of an object is to use Object.getPrototypeOf()
.
In your case .prop
is referencing an object literal, so you already know that the prototype is Object.prototype
.
Object.getPrototypeOf( {} ) === Object.prototype; // true
Note that it is almost always a bad idea to extend Object.prototype
.
"Maybe I'm taking the wrong approach (in trying to permanently modify prop), but I'd at least like to know why the code above doesn't work."
If you're just trying to modify the object referenced by .prop
, then simply do:
obj.prop.new_attr = "some_value";
You can acplish what you are trying to do but you need to add the prop object to the constructors prototype:
var Obj = function() {};
Obj.prototype.prop = { bar: 'bar value' };
var obj_1 = new Obj();
console.log(obj_1.prop.bar); //bar value
obj_1.prop.foo = 'foo value';
var obj_2 = new Obj();
console.log(obj_2.prop.foo); //foo value
Because the prop attribute is empty. Before you'll be able to modify object.prop, you need to initialize prop first to a default value.
See the following references: Extending JavaScript Objects and Classes
Introduction to Object-Oriented JavaScript
A re-introduction to JavaScript
HTH. Cheers.
本文标签: JavaScript modify prototype of an object39s variableStack Overflow
版权声明:本文标题:JavaScript: modify prototype of an object's variable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744621741a2616070.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论