Prototyping Within Library - Extend Or Super-class The Native String Object
Apr 21, 2011
I have a few String prototypes such as String.prototype.EscapeReg = function () { return this.replace(/[-[]{}()*+?.,\^$|#s]/g, "\$&"); }; // Escapes characters for use with a regular expressionI also have my own class/ library which is used like this var adg = new AndyG_ns.ADG_Utils(); adg.StartClock('AndyClock','dd mmm yy hh:nn'); // etc.What I would like to do is to only add the prototype to my library (not to the global namespace). The end result I'm looking for is to use code such as:
var adg = new AndyG_ns.ADG_Utils();
var myString = new adg.AString();
var parsed = myString.EscapeReg();
In addition, I want to be able to also use/create my special string sub-class within my library. I suppose I'm saying that I would like to extend or super-class the native String object.
I was wondering whether someone could shed some light on the following. Using inheritance in Java one can override a function f() (or is it overload?) in the child and then do: public f() { super.f(); ... } in the child to first execute the parent stuff to be followed by the additional child stuff.
Is there a way to accomplish this in JS as well and if so how?
I've already figured out the normal inheritance bit and complete function overriding. I'm just looking for the above case.
How can I subclass a native class to get my own class with all the function of the native clas, plus correct instanceof behaviour?
The scenario I'm thinking of is something like
function MyArray() { Array.apply( this, arguments ); } MyArray.prototype = new Array(); MyArray.prototype.constructor = MyArray;
var marr = new MyArray(); marr[0] = "abc"; marr.length == 1; // true marr instanceof MyArray; // true
But this seems impossible due to the Array constructor returning a new object even when called with my own "this" in the apply() above. Can this be solved in any way?
I'm apparently misunderstanding what I'm reading on prototyping. My main task is to squeeze some performance out of an app that's a bit slow on IE, and it looks like large Arrays and their overhead may be part of the problem. I'm trying to replace those with my own array type based on Object and extend it with helper functions like .length. Here's a munged sample of what I've tried:
Code: function BaseController(el) { var that = this; this.defaultAction = function() {
[Code]....
What is the proper method here so that el will be defined in the super "class".? I know I saw something on stack overflow a couple of days ago but can not seem to find it again.
admin: Something is up with the code tags, why the system is double posting the code. Does HIGHLIGHT=JS not exists anymore? – That seemed not be working.
As I know,it's not well to extend Object.prototype derictly. In the Prototype(JS Framewoke),there is no extend Object.prototype. It only add some static method for Object class.I want to konw the reason.
How to extend the constructor for the date object of the javasccript so that whenever a call is made to the constructor, I want to perform a particular action? Basically how to define wrappers for default javascript methods or objects like Date() so that I can perform some action and then invoke the original method? So basically if I have something like var a = new Date(); I want it to (say) alert the value of the date everything Date() is called and then execute the default date constructor.
What happens if you do the following? - That is deep copy a jQuery selector.
[Code]...
I'm concerned whether the myObj.selector object will deep copy the whole of jQuery as part of the process. My initial tests did not show any obvious speed hit, but it is rather a basic test right now.
I am using GreaseMonkey to load jQuery 1.3.2 (there is a bug with the latest version of jquery and GM) and jQuery UI 1.8.0.I am using jQuery via GM to manipulate the GUI of a content management system. This CMS uses its own JS library to dynamically add stuff to the dom.
Question:How can I target a dom element that was added to the dom via this other JS lib?In other words, the CMS will add a div to the dom, and I am not sure how to tell jquery to wait for these elements to "be there" before applying the jquery goodness. Specifically, I would like to do this:
$(function() { $('#zen1227').resizable(); });
But "#zen1227" does not "appear" until later via this other JS library.
One thing I haven't figured out about javascript is the treatment of __proto__.
Inheritence, whether prototypes or class-based, is just a shorthand form of delegation (leaving aside dynamic dispatch).
In Java a derived class serves as a wrapper for its superclass. The derived class can easily access members of its super class using the nice "super" keyword. Why, in javascript, is this functionality buried in the unofficial "__proto__" property? It seems that it must have been the intent of the language designer that explicitly accessing the prototype chain is a bad thing for some reason, although I can't see any reason.
By googling, you can find a lot of weird hacks to add "super"-like functionality to javascript, although many of them look misguided to me. It certainly seems that this is a commonly confusing part of the language.
If __proto__ were an official part of the language, implementing a decorator or proxy pattern would be nicely simplified compared to class-based inheritence. The "before-and-after" style of AOP (which is just another style of shorthand for delegation) would be possible without any crazy tricks.
So, anyone care to set me straight? Why isn't __proto__ or something like it a well defined part of javascript? Shouldn't it be?
I tried load method super as smartupdater orPeriodicalUpdater (Prototype). Now the problem is that I have to build a cycle (loop) and each time I have to change the time (that I take from database) so how method (function) can I use to load external code (example load()) modifying continuosly the timeout?
When I use this function, one of the keys in the iteration will be the new function that I have created.
The following example would alert the following: "key1", "key2", "keyExists". The last one is my concern. Obviously their are other browser-defined functions available for Objects that don't show up when iterating through the object. I thought Object.prototype.functionname was the methodology for that but apparently not. Is there a way to achieve the effect I am looking for? Code:
We all know (and love!) the fact that Mozilla exposes element constructors (HTMLParagraphElement, for example) for prototyping. Turns out Opera 8 allows you do to the same thing.
So this leaves Safari, which has actually allowed you to do this since 1.0, *but* doesn't publicly expose the constructors. The below code exports constructors into public variables matching those in Mozilla and Opera 8:
/* HTMLElement Prototyping in KHTML and WebCore Copyright (C) 2005 Jason Davis, www.jasonkarldavis.com Additional thanks to Brothercake, www.brothercake.com
This code is licensed under the LGPL: http://www.gnu.org/licenses/lgpl.html */
function HTMLElement() {} HTMLElement.prototype = HTMLHtmlElement.__proto__.__proto__; var HTMLDocument = document.constructor; var HTMLCollection = document.links.constructor; var HTMLOptionsCollection = document.createElement("select").options.constructor; var Text = document.createTextNode("").constructor; var Node = Text; }
In Opera < 8, all elements inherit directly from Object(), so you can still prototype Object() if you need to do element prototyping. Internet Explorer's elements *don't* inherit from Object, oddly enough, so who knows with that browser. In any case, there you go. It also happens to work in Konqueror (AFAIK).
Is it possible to create a function that will find a class name or id name and then assign that name as variable string?
For example, my body has a class name:
<body class="Sunday">
I need to have a function (using jquery or just regular javascript) that will determine that class name and then assign it to a variable named bodyClass, so that bodyClass="Sunday".
I am ok with using objects creating classes if someone else defines, but when it comes to defining my own, I hit a nasty brick wall... I am using an XML/XSLT wrapper called Sarissa to help with programming a utility to transform XML into HTML in different views. For this to happen, I have created a Loader class which loads in XML required. I am aware of prototyping for binding methods to objects (as opposed to replicating the same method every time an instance is created)... The aim being I want to create a progress bar for the essential files that need to be loaded in. Presently I have them load in Synchronous mode just to get the utility working, which I know is poor, so would like to address it.
Is there anyway to have a CSS class returned as an object? This would be rather useful to feed, for example, to the .animate() function. There is no way to animate directly to a CSS class as destination, is there?
I'd like to announce release 1.0.7 of JNEXT (JavaScript Native Extensions). JNEXT is an open source framework for securely accessing the full range of native OS resources (files, databases, sockets etc.) by using JavaScript from within a Web Page. It is light weight, cross platform, cross browser and designed with simplicity in mind....
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until recently -- or maybe I should just speak for myself.)
The fact that JSON is more elegant goes without saying, yet I can't seem to find a way to use JSON the way I *really* want to use it: to create objects that can be instantated into multiple instances without prototyping. I've seen (and used) JSON for singleton object instances -- this not a problem and this is how it works right out of the gate.
But given the following custom object written the past "normal" way, I would like to write it in JSON format, and then be able to create new instances from the one definition. Here's an example using the "old way" most who have been writing JavaScript for years have seen:
But neither are really as close to pure JSON as I would like, so that I can instantate those:
var hisPair = new Two( 11, 22 ); var herPair = new Two( 33, 44 );
What I'd like is a way in PURE JSON to be able to create the Two class (as an example) using pure JSON. I've not seen anything yet on the web that addresses this directly aside from some pages which require you to include another JS to allow "deep embedding" of classes using other helper "classes" (that are created the "old way" it seems), etc.
The best I've found so far on using pure JSON to create a class that allows *multiple* instances is something like this:
function Two( x, y ) {
var class = { x : x, y : y, sum : function { return this.x + this.y } max : function () { return this.x this.y ? this.x : this.y } min : function () { return this.x this.y ? this.y : this.x } pow : function () { return Math.pow( this.x, this.y ) } };
for (var element in class) this[element] = class[element];
}
Now *THAT* works, but it's still not as "pure" I would like. But it's acceptable for now, I guess, since I *am* creating the entire "class" as a JSON object, and I consider the outside function "wrapper" as the necessary "constructor." But I keep wondering... There HAS to be a better way.
I'm just wondering if anyone knows of a place that discusses JSON used in situations like the above. Again, I've seen an ABUNDANCE of pages and sites that discuss JSON in Singleton usage, but nothing that discusses it as I am wanting here.
I have a javascript object which dynamically generates a table adding, deleting and moving rows as the user clicks on buttons or links. Problem is when I generate a table row and add the javascript method call to my class, I have to put the object instance name variable of the class in order for it to be called from the onclick=function(). This is seriously limiting, but I'm stuck for a way round it. Heres a edited of the code so you get the idea....
Instantiating the object :-
var dtl = new DynamicTableList("table1", $ {myObject.allFieldsAsJavaScriptArray}, true, true, true);
My javascript class DynamicTableList, note the dtl javascript object instance variable being referred to in the addRow function. How can I avoid this???
if (showDelete) { var cell2 = document.createElement('TD'); var inp2 = document.createElement('IMG'); / ************************************************** ***********************************************/ inp2.onclick=function(){dtl.delRow(this);} // Have to specify dtc!!!!!!!! / ************************************************** ***********************************************/ inp2.title='Delete' inp2.alt='Delete' inp2.src='images/delete.gif' cell2.appendChild(inp2); row.appendChild(cell2); }
...
tbody.appendChild(row);
this.processRows(); };
this.moveRow = function(node, vector) { }; }
Obviously the code dtl.delRow(this); is being dynamically generated, but how do I replace the dtl instance name with something that'll work whatever the user of this class calls the instance of it!