STORE = {
item : function() {
}
};
STORE.item.prototype.add = function() { alert('test 123'); };
STORE.item.add();
我已经努力研究这个问题很久了,但是还是不知道为什么它不起作用。然而,当我使用以下代码时,它可以正常工作:
STORE.item.prototype.add();
STORE = {
item : function() {
}
};
STORE.item.prototype.add = function() { alert('test 123'); };
STORE.item.add();
我已经努力研究这个问题很久了,但是还是不知道为什么它不起作用。然而,当我使用以下代码时,它可以正常工作:
STORE.item.prototype.add();
var STORE = {
item : function() {
}
};
STORE.item.add = function() { alert('test 123'); };
STORE.item.add();
如我之前所说,原型对象的典型用法是通过使用new操作符调用构造函数来实例化对象,例如:
function SomeObject() {} // a constructor function
SomeObject.prototype.someMethod = function () {};
var obj = new SomeObject();
所有的SomeObject实例都会继承自SomeObject.prototype的成员,因为这些成员将通过原型链进行访问。
JavaScript中的每个函数都有一个原型对象,因为无法知道哪些函数是要用作构造函数。
经过多年的等待,当 JavaScript (ES2015) 到来时,我们终于拥有了 Object.setPrototypeOf() 方法。
const STORE = {
item: function() {}
};
Object.setPrototypeOf(STORE.item, {
add: function() {
alert('test 123');
}
})
STORE.item.add();
__proto__
属性实现此操作。以防万一有人现在或将来查看此处。const dog = {
name: 'canine',
bark: function() {
console.log('woof woof!')
}
}
const pug = {}
pug.__proto__ = dog;
pug.bark();
然而,在这种情况下添加原型的推荐方法是使用Object.create。因此,上述代码将被翻译为:
const pug = Object.create(dog)
pug.bark();
或者你也可以使用Object.setPrototypeOf,正如其中一个回答中所提到的。
希望能对你有所帮助。
var myObject = JSON.parse(myJSONtext, reviver);
myData = JSON.parse(text, function (key, value) {
var type;
if (value && typeof value === 'object') {
type = value.type;
if (typeof type === 'string' && typeof window[type] === 'function') {
return new (window[type])(value);
}
}
return value;
});
STORE = {
item : function() {
}
};
typeof STORE;
来检查。它应该返回'object'。如果您键入STORE.item;
,它将返回'function...'。STORE.item = function() { alert('test 123'); };
STORE.item;
,它仍应返回'function..'。 尝试STORE.item();
,然后将显示警报。
Object.create(prototype)
。更多信息在此处。 - JohnnyQ