FAQ Database Discussion Community


Is it okay to declare a new subclass as a prototype method in JavaScript?

javascript,prototype,prototypejs
I have a class that has a few nested subclasses, but I'm not sure what the correct syntax should be. This is what I was thinking of doing. It works out well, but maybe it's not the best coding practice. function AClass() { this.myB = new BClass(); } AClass.prototype.BClass() {...

From prototype to real APP

ios,user-interface,prototype,converter
I am a starter now developing my own IOS APP, but ran into the trouble: I really want to work out some cool UI, and do find lots of tools that will do exactly what I am thinking, however they seems to only give a prototype design. I am wondering...

Unwanted Javascript effect: Prototype is sharing closure between instances

javascript,closures,prototype
I'm making a game with timed levels. A level is 2 minutes long, and a countdown timer is displayed in the upper right corner. Mario style. One way to keep track of the elapsed time would be to have my Level object have elapsed as a member variable. Level.init =...

Why prototype is not available in simple JavaScript object [duplicate]

javascript,prototype
This question already has an answer here: Why is JavaScript prototype property undefined on new objects? 4 answers I am trying to understand the JavaScript prototype and I am bit confused.There are tons of tutorials out there and each has different explanation on it. So I don't know where...

Function as a prototype's objects's property in Javascript?

javascript,function,object,prototype
I have a code similar to this: var thing = function (prop1, prop2, prop3) { this.prop1 = prop1; this.prop2 = prop2; this.prop3 = prop3; }; function assignProp1 () { return 'value1'; //Function simplified for the question } function generateThing () { return new thing(function () {return assignProp1();}, 'value2', 'value3'); }...

javascript constructor.prototype inheriting another constructor.prototype [duplicate]

javascript,oop,inheritance,prototype
This question already has an answer here: Why wouldn't I use Child.prototype = Parent.Prototype rather than Child.prototype = new Parent(); for Javascript inheritance? 3 answers Here is my problem: Let`s say I have a constructor A() with prototype X; And now I have another constructor B which I want...

marionette controller object, create dynamic prototype methods?

javascript,backbone.js,prototype,marionette
I am using marionette for an app that has many pagess. The controller/router method is repetitive, in each method the view is instantiated and the appRegion shows the view. I would like to create the methods inside a loop. var Controller = Marionette.Controller.extend({}); for(i=0;i<10;i++) { // build dynamic controller methods...

Bind this argument to named argument [duplicate]

javascript,jquery,prototype
This question already has an answer here: Using bind for partial application without affecting the receiver 1 answer In the case I have a code structure as follows : Thing.prototype = { doSomething: function() { $(selector).click(this.handleClick.bind(null, this)); }, handleClick: function(self, event) { console.log(this); //Window console.log(self); //Thing } } How...

How to use prototypes such as modules in Node.js?

javascript,node.js,express,prototype
I create a folder called helpers, and inside that, create the array.js file Inside my array.js, i have this code: Array.prototype.inArray() { for(var j in this) { if (this[j] === arguments[0]) { return true; } } return false; } And i want be able to use like a module: myArray.inArray(myargument);...

Javascript difference between MyClass.prototype = {} and MyClass.prototype.method [duplicate]

javascript,prototype
This question already has an answer here: Defining a Javascript prototype 5 answers This is one thing I was wondering for a long time. But first example code for both Type A var JavaScriptClass = function () { }; JavaScriptClass.prototype = { myMethodOne: function() { }, myMethodTwo: function() {...

Need to add a custom type and use a prototype property within my form

javascript,html,methods,prototype,custom-type
I am trying to create a custom type and then add a method to the custom type using its prototype property within the dummy form I have created. I am trying to wrap my mind around how I could create a custom type that would essentially create a "new subscriber."...

Object creation patterns using Object.create()

javascript,inheritance,prototype,factory
I'm stuck on figuring out how to do multi-level inheritance while using Object.create() as opposed to traditional constructors. I've opened a fiddle here . We have two types of objects, programmers, and a "subclass" front-end developers. Programmers inherits from the programmer prototype object, and as you can see, all programmers...

Is it possible to using Javascript prototypes without using the “new” keyword?

javascript,oop,prototype
The fact that Javascript uses functions to create objects was confusing to me at first. An example like this is often used to highlight how prototypes work in Javascript: function Car(){ this.setModel=function(model){ this.model=model; } this.getModel=function(){ return this.model; } } function Bus(){} Bus.prototype=new Car(); var obj=new Bus(); obj.setModel('A Bus'); alert(obj.getModel('A Bus');...

Why requestAnimFrame need bind(this)

javascript,prototype,bind,requestanimationframe
Why does window.requestAnimFrame must be called like this: window.requestAnimFrame(this.__proto__.animate.bind(this)); and not like window.requestAnimFrame(this.__proto__.animate);. My js-class looks like: Game = function (moduleConfig, gameConfig) { this.moduleConfig = moduleConfig; this.gameConfig = gameConfig; // Game-Commands this.keyCommands = { moveLeft: false, moveRight: false }; // Some init stuff requestAnimFrame(this.animate.bind(this)); return this; } /** * Init...

Javascript static vs instance, prototype keyword

javascript,static,prototype
I want to know the difference between the following two code snippets What I understand is this is static because without creating an instance with new keyword, getCookie and setCookie functions can be called. var CookieHandler = function () {}; CookieHandler.getCookie = function (key) { }; CookieHandler.setCookie = function (key,...

Call Prototype Object Method in JQuery Event Handler

javascript,jquery,prototype
I have an object called Breadcrumb, which has a function expandEllipses. The following works fine: mbc = jQuery('#breadcrumb').breadcrumb({ items : initItems }); jQuery("body").on("click", ".breadcrumb .breadcrumbEllipses", function(e) { mbc.expandEllipses(); }); However, I was wondering how to do this in a jQuery event handler where I don't have the object right there...

Static methods in JavaScript

javascript,static,prototype
If I have a class declared in prototype.js var ClassFoo = Class.create(); ClassFoo.prototype = { initialize: function() { }, type: 'ClassFoo' }; If I declare a method ClassFoo.doBar = function() { log("foobar") } Is it the same as/equivalent to creating a static method in java ? Can an object of...

How can I check instanceof without the proto chain in javascript?

javascript,prototype,prototypal-inheritance
How can I check instanceof without the proto chain in javascript? var EventEmitter = require('events').EventEmitter; var Foo = function(){ }; Foo.prototype = EventEmitter.prototype; var Bar = function(){ }; Bar.prototype = EventEmitter.prototype; var f = new Foo(); var b = new Bar(); f instanceof Foo; //returns true b instanceof Bar; //returns...

Modifying all members of a class via an instance method

javascript,prototype
In JavaScript, is it possible to call an instance method on an object that affects all of its siblings? For example, say I have the following class: function Thing() { this.active = false; } Thing.prototype = { constructor: Thing, activate: function() { this.active = true; }, deactivate: function() { this.active...

How to vertically align these elements inside a span?

html,css,user-interface,prototype,user-experience
Here is the prototype I am trying to implement. Here is what I have right now What I am trying to do right now is vertically align all the elements(spans with image and text) - My Account, Cards, Travel, etc.. Here is my HTML and CSS for this section HTML:...

Magento jQuery / Prototype Issues in 1.9 After upgrade

jquery,magento,prototype,magento-1.9
After doing an upgrade from 1.3 ( and only moving theme and a couple of extensions - so reasonably clean install) , I am having a lot of jquery issues and prototype issues. For example home page: Class is not defined , Ajax is not defined. I'm not sure where...

Prototyping an Angular Directive

javascript,angularjs,prototype
Based on instruction from this question, I have added the following code to my application within the config stage: $provide.decorator('formDirective', function($delegate) { var directive = $delegate[0]; directive.controller.prototype.inputs = {}; console.log(directive.controller); return $delegate; }); All I want to do is create another field and a few methods to the existing angular...

Array splice prototyping

javascript,arrays,node.js,prototype
I'm trying to extends Array splice function in my NodeJS app, unfortunately it doesn't work, I get malformed result. It seems my array isn't one : var EggDBArray = function(){ } EggDBArray.prototype = Array.prototype; EggDBArray.prototype.splice=(function(){ var original = Array.prototype.splice; return function() { return original.apply(this,arguments); }; })(); When I run splice...

Understanding prototype object creation with 'Object.create()' instead of 'new' keyword

javascript,object,constructor,prototype
I came to a code that contains these lines var data = function() { function Metadata() { /*some initialization here*/ } Metadata.prototype = Object.create(Backend.prototype); Metadata.prototype.constructor = Metadata; return Metadata; } I struggle to understand what is actually going on, and how to use the returning object. If I understand it...

How to create a Javascript Hash Table / Associate Array Prototype

javascript,prototype,associative-array
With a associative array such as: var m = {}; m['a'] = {id:1, foo:'bar'}; m['b'] = {id:2, foo:'bar'}; Is it possible to create a prototype such as: Array.prototype.hello = function() { console.log('hello'); } m.hello(); This fails because m is an object, so I tired: Object.prototype.hello = function() { console.log('hello'); }...

Reference to Object.prototype.toString.call resulting in 'TypeError: undefined is not a function'

javascript,reference,prototype,this,typeerror
I'm encountering an unusual situation. I store a reference to Object.prototype.toString.call, in an attempt to make a shortcut, calling it as the assigned variable results in a TypeError, whereas calling it directly each time does not. Can anyone explain what is actually happening, as opposed to what I believe I...

Clone prototype function keeping scope

javascript,prototype
I have somewhat of an odd use case, but here it goes (below is an example, but the methods are named somewhat differently); There's a prototype function name bootstrap on an object I'm using, which calls a function create. I want to modify it (without changing the prototype) in order...

JS Inheritance: calling the parent's function from within the child's function

javascript,oop,inheritance,prototype
There must be something I don't understand about the JS object model. From these resources: Prototypes Basic OOP in JS- Inheritance Object.create() I have gathered what I think, or thought, was an accurate mental representation of the object model. Here it is: All objects have a property, which the docs...

Way to provide “this” to the global scope?

javascript,object,prototype,promise,bluebird
I'm working with a debounce function found here in this stackoverflow post. It's a promise that allows for throttling requests. The debounce function won't work for some reason when it's nested within a function because the setTimeout calls to the request seem to get sent all at once. It needs...

Magento form validation of hidden values

javascript,magento,prototype
I have problem with default Magento form validation. I'm using accordion for checkout page, so when I submit form, some fields are hidden. I noticed all hidden fields are passing validation, even if they are empty (required-entry class used). Is there any way to force validation script to check all...

Prototype difference between object.create and new Object

javascript,object,prototype
//The last link of the prototype chain always be Object.prototype. var o = {"name":"kannanrbk", "age": 21}; //extending object. var no = Object.create(o); //Now the new object is linked to the old object o. no.name = "Bharathi Kannan R"; console.log(o.name); //Still be 'kannanrbk'. Because, this prototype chain will be used only...

How can I return the array object from Array's prototype function?

javascript,arrays,inheritance,prototype,chaining
I have a programming exercise to create two prototypes of Array, they are both functions. I have put my code below. One will be called on the other as shown in the last line. I am trying to get the second function to modify the value that would have been...

How can I use DOMStringMap in Javascript?

javascript,prototype
I was experimenting with the DOMStringMap object and I don't understand how it works. I was trying to change the prototype of a DOMStringMap object but it behaves oddly: Object.setPrototypeOf(element.dataset,{}); // sets prototype properly element2.__proto__={}; // sets prototype to "[object Object]" in Chrome; in FireFox, nothing happens If I changed...

Understanding JavaScript Prototypes

javascript,prototype
Am messing around with prototypes to get a better understanding of how they work. I can't work out why I can't call hideHeader, whereas I can access a variable (this.header.el) function App() { this.init(); this.el = document.getElementById('box'); } App.prototype.init = function () { document.write('hello world'); this.header = new Header(); this.header.hideHeader();...

Can I save object prototype in local storage?

javascript,prototype
I have JS object with custom methods as prototype (e. g. Foo.prototype.myAwesomeMethod). If I load my object in a localStorage and get it later I'll loose these methods. var foo = new Foo() console.log(foo.myAwesomeMethod()) // WIN localStorage.setItem('foo', foo) foo = localStorage.getItem('foo') console.log(foo.myAwesomeMethod()) // FAIL... Is it possible to save the...

Prototype declared function is not a function

javascript,prototype,prototype-programming
var AnArray=(function(){ var anArray=[]; AnArray.prototype.getAnArray=function(){ return anArray; } AnArray.prototype.setArray=function(id,val){ anArray[id]=val; } }); var objAnArray=new AnArray(); console.log(objAnArray.getAnArray()); When I try to call objAnArray.getAnArray(); it returns that it is not a function However this below works fine var Index=(function(){ var Index=1; Index.prototype.getIndex=function(){ return Index; } Index.prototype.setIndex=function(val){ Index=val; } }); var objIndex=new Index();...

How to add Object.prototype.x? set to enumerable:false

javascript,syntax,prototype,enumerable
$('example') console logs foo {word: "example", letter: function} ^ The log showed me letter is a prototype function of foo var foo,$; (function() { foo = $ = function(word) { return new foo(word); }; var foo = function(word) { //#A this.word=word; console.log(this.word); return this; }; foo.fn = foo.prototype = {...

Why does util.inherits create a new object that inherits from the super constructor's prototype? [duplicate]

javascript,node.js,inheritance,prototype
This question already has an answer here: Prototype copy vs Object.create() vs new 2 answers In the source for util.inherits they call object.create to create a new object whose prototype is the prototype of the super constructor. ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true,...

How to check if a variable is an ES6 class declaration?

javascript,class,prototype,ecmascript-6
I am exporting the following ES6 class from one module: export class Thingy { hello() { console.log("A"); } world() { console.log("B"); } } And importing it from another module: import {Thingy} from "thingy"; if (isClass(Thingy)) { // Do something... } How can I check whether a variable is a class?...

how do i create an Object.prototype clone

javascript,object,prototype,prototype-chain,prototype-oriented
I have an incomplete clone of Object.prototype, made to the best of my knowledge, can you show me how to finish it!? The Code function duplicate_object_prototype(){ var aRef=[ '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', '__proto__' ]; var clone = Object.create(null); for(var i in aRef){ var...

Issue replacing input value in array

javascript,jquery,html,arrays,prototype
I did an example about replacing the input value when the row is deleted but is not working (this is not a static example). <script src="./edit_files/prototype.js" type="text/javascript"></script> <script src="./edit_files/application.js" type="text/javascript"></script> <div class="contact"> <table border="0"> <tr> <td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1"...

Trying to spy (Jasmine) on Array.prototype methods causes stack overflow

javascript,jasmine,prototype,spy,testem
This is pretty odd. Using the testem runner with jasmine2 and the following spec executes (though it correctly flags that there are no expectations): describe('Spying on array.prototype methods', function(){ it('should work this way', function(){ spyOn( Array.prototype, 'push' ).and.callThrough(); // expect(1).toBe(1); }); }); However, add an expect (any expect!) and it...

HTML