我想爲我的所有對象(包括「原始」對象(如字符串和數字))添加一個$ error元素。操作JS原型
我有以下的codepen,只是將這個值(通過函數)添加到Object類。
http://codepen.io/anon/pen/nglbL
爲方便起見,這裏是代碼: -
Object.prototype.setError = function (str) {
this.$error = str;
this.$errorObj = { };
console.log("value of object is " + this.toString());
console.log("Setting error to " + this.$error);
};
Object.prototype.getError = function() {
console.log("error is " + this.$error);
console.log("error object is " + this.$errorObj);
return this.$error;
}
var obj = {
"str" : "string me!",
"bool" : true,
"int" : 1
}
obj.str.setError("error");
console.log("Retriving error and it is " + obj.str.getError());
很顯然,我不明白的原型繼承是如何工作的。
謝謝。
「try ... catch」和「throw」有什麼問題? – Blender
我97%肯定這是由於字符串_literal_和字符串_object_之間存在差異,因爲他在他的代碼中使用了'obj.str'而不是'obj' ... –
真實這裏的問題是你想完成什麼?爲什麼你想讓每個對象都有這些方法?你意識到這會傳播到JavaScript中的所有東西(即數組,函數等),因爲它們的鏈中都有Object.prototype – tkone