[英]Javascript Object.prototype is undefined
I'm trying to create a simple extensible "class" in javascript but when setting property in a prototype it tells that the prototype is undefined: 我正在尝试在javascript中创建一个简单的可扩展“类”,但是当在原型中设置属性时,它告诉原型是未定义的:
Class = {};
Class.extend = function(obj) {
var result = Object.create(this);
if (obj) {
for (var key in obj) {
if(typeof obj[key] == 'function'){
console.log(result);
result.protorype[key] = obj[key];
}else{
result[key] = obj[key];
};
};
result.prototype.constructor = result;
}
return result;
}
var a = Class.extend({
username: "matteo",
password: "nn te la dico",
getByUsername: function() {
return this.username;
}
});
console.log(a, Class.isPrototypeOf(a));
The problem happens when trying to set the property 'getByUsername' passed when defining "a", if you look at the console it will report that: 当在定义“a”时尝试设置属性'getByUsername'时会发生问题,如果你看控制台,它会报告:
Uncaught TypeError: Cannot set property 'getByUsername' of undefined
And the "result" logged has the properties "username" and "password". 并且记录的“结果”具有“用户名”和“密码”属性。
PS It will work only in IE > 8 PS它只能在IE> 8中使用
Here is a fiddle http://jsfiddle.net/paglia_s/z62eA/ 这是一个小提琴http://jsfiddle.net/paglia_s/z62eA/
You have a typo. 你有一个错字。
result.protorype[key]
should be result.prototype[key]
result.protorype[key]
应该是result.prototype[key]
Just don't create your object by using : Class = {}; 只是不要使用以下方法创建对象:Class = {};
But by using : Class = function(){}; 但是通过使用:Class = function(){};
Which creates a new object with a prototype.. 这会创建一个带有原型的新对象..
Your code will look like so : 您的代码将如下所示:
Class = function(){};
Class.extend = function(obj) {
var result = Object.create(this);
if (obj) {
for (var key in obj) {
if(typeof obj[key] == 'function'){
console.log(result);
result.prototype[key] = obj[key];
}else{
result[key] = obj[key];
};
};
result.prototype.constructor = result;
}
return result;
}
var a = Class.extend({
username: "matteo",
password: "nn te la dico",
getByUsername: function() {
return this.username;
}
});
console.log(a, Class.isPrototypeOf(a));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.