Is there any way to clean up all the Obj.prototype.field =
statements in my javascript code? I am using jQuery. I want to do the same thing except not have every other word in my code be prototype
. Maybe what I'm asking is impossible -- if so, just let me know and that will be the answer.
I found this to be an ungoogleable question because there is a js library named "Prototype"...
Use jQuery.extend . The properties of the second argument will be copied over to the first one:
$.extend(Obj.prototype,{
field1: "hi there",
func1: function(){
//do stuff
}
});
This is what jQuery uses internally, jQuery.fn being an alias for jQuery.prototype:
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}, ...
You could also do something like
var p = Obj.prototype;
p.newMethod = function(window.alert("Hi! I live"));
p.newProperty = false;
maybe just:
Obj.prototype = {
run: function(){},
fooBar: function(test1,test2){}
};
?
have a look at the "extend" functions of libraries like jQuery and YUI3
http://api.jquery.com/jQuery.extend/
http://yuilibrary.com/yui/docs/yui/yui-extend.html http://yuilibrary.com/yui/docs/yui/yui-extend.html
Also look at merge (jQuery, YUI3) and augment (YUI3) and at the usage.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.