如何解决JavaScript Object原型函数无法按预期使用
| 如果您打开此JSFiddle,您应该在Firebug / Chrome开发工具中看到调用ѭ0is时会引发异常,因为ѭ1不存在。 但是,如果您在控制台中运行Object.method
或Function.method
,您会发现它们确实存在于各自的原型中。
我确定这是一个简单的继承问题,但是在这一点上我无法理解为什么method
方法没有冒充到x
对象。
代码如下:
// Crockford\'s Object.create shim
if (typeof Object.create !== \'function\') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
// Add a method creation function to the Function prototype
// Note that on this line I\'ve also tried:
// Object.prototype.method = Function.prototype.method = function (name,func) {
Function.prototype.method = function (name,func) {
this.prototype[name] = func;
return this;
};
// Create our object
var x = Object.create({});
// Add common methods to the prototype of our new object
x.method(\'logNumber\',function (num) {
console.log(num);
});
// Try it out
x.logNumber(6);
解决方法
[注意] jsfiddle目前似乎已关闭,因此我无法检查您的代码
该功能:
Function.prototype.method = function (name,func) {
this.prototype[name] = func;
return this;
};
向Function原型添加一个方法。使用构造函数创建对象:使用new
关键字调用的函数将创建其构造的对象的实例。在Object.create
\'shim \'中,构造函数为F
,但shim返回其实例(new F()
)。
变量“ 5”不是构造函数,而是实例。您只能从Function.prototype调用method
,因此x.method
是undefined
。
不使用Object.create
可能会向您显示其工作方式:
function X(){}; //=> new X will create an instance of an empty Object
X.method(\'logNumber\',function (num) {
console.log(num);
}); //=> call \'method\' from the constructor: now it\'s working
var x = new X; //=> create an instance
x.logNumber(6); //=> behold!
, 这可行,但是没有控制台
Object.prototype.method = function (name,func) {
this[name] = func;
};
http://jsfiddle.net/mplungjan/jhBjs/
, 我相信您要的不是20英镑,而是19英镑。另外我猜你想在对象上:
Object.prototype.method = function (name,func) {
this.[name] = func
return this
}
鉴于您已经在使用Crockford的对象了,如果您并非所有22岁的孩子都需要使用此对象,则可以执行以下操作:
var X = { method: function (name,func) {
this[name] = func
return this
}
var x = Object.create(X)
, var x,x是一个Object,而不是一个函数,这就是为什么您需要使用
Object.prototype.method = function (name,func) {
this[name] = func;
return this;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。