[英]How to extend a javascript object to include a method using _.extend or $.extend?
For example using Underscore library, the following code works: 例如,使用Underscore库,以下代码有效:
var myobject = {};
_.extend(myobject, {
method: 'demo'
});
Here, myobject.method
prints demo. 在这里,
myobject.method
打印演示。 But the following example does not work, myboject.method is undefined , when I set the value of method
to be a function instead of a string: 但是以下示例不起作用,当我将
method
的值设置为函数而不是字符串时, myboject.method是undefined :
var myobject = {};
_.extend(myobject, {
method: function() {
return 'demo'
});
});
Remove the extra );
删除多余的
);
var myobject = {};
_.extend(myobject, {
method: function() {
return 'demo'
} // ); <-- remove this
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.