FAQ Database Discussion Community


Javascript class inheritance. Subclass changes main class's properties?

javascript,inheritance,prototype,prototypal-inheritance
var Main = function(){}; Main.prototype = { 'times' : 0, 'request': function(){}, ... }; var SubA = function(){}; SubA.prototype = new Main() // same with Object.create(Main.prototype); SubA.prototype.constructor = SubA; var SubB = function(){}; SubB.prototype = new Main() // same with Object.create(Main.prototype); SubB.prototype.constructor = SubB; Now: var sub_a = new SubA();...

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...

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...

Javascript object as parent for another js object

javascript,oop,prototype
Could you explain me how to do in JavaScript such thing : Create one object. Create second object. Set first object as a parent to second object. Add second object as child to first object. It sounded simple to me as Java developer but I am confused right now. Demo:...

Constructor function - in simple namespace - Javascript

javascript,object,namespaces,prototype
In want to define a function-constructor inside a namespace. The way in which I defined the constructor till now was a simple constructor function without NS, combined with prototypal inheritance. The code looked kind of like: function mySuperObject() { var self = this; self.p1 = ""; self.p2 = "jkejie"; //...

Javascript class method returning array but not assigning it to a new variable

javascript,arrays,prototype
I have the following code var Datos = function(){ this.salas = ['something','other']; } Datos.prototype.getSalas = function(){ return this.salas; } Then, If I do var datos = new Datos(); var myArray = datos.getSalas(); Why "myArray" var is now a function and not an array? How can I convert to an array...

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();...

Binding Object Prototype Functions to Object in Javascript

javascript,prototype,call,this,bind
Background I have a prototype object that has dozens of functions that access info from a list like this: var prototype_object = { yellow: function(list) { return list[this.type+'_yellow']; }, green: function(list) { return list[this.type+'_green']; }, // ... 50 more functions here } The 'this.type' is supposed to come from the...

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...

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"...

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...

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...

In Javascript, why does Object.getPrototypeOf([1,2]) returns an empty list?

javascript,node.js,google-chrome,object,prototype
In Chrome 42.0, I assign a value to myArray using var myArray = [1,2], I expect Object.getPrototypeOf(myArray) will be like this (screenshot from here).. However, when I evaluate the code in REPL, I only got an empty list: Does anyone have any ideas about this?...

Determine origin of method in prototype chain

javascript,oop,prototype
Lets say that i have the following prototype-chain. function Vehicle() {} Vehicle.prototype.drive = function() { console.log("I'm driving"); }; Vehicle.prototype.turnOn = function() { console.log("Wrom wrom"); }; function Car() {} Car.prototype = new Vehicle(); Car.prototype.honkHorn = function() { console.log("*loud sound*"); }; var car = new Car(); I'm iterating over the car-object with...

get dynamic property defined in prototype during JSON.stringify

javascript,prototype,prototypal-inheritance
I've defined an enumerable property in the prototype object and would like it to appear when I convert a prototyped object to JSON. My first idea was to set it in toJSON but because I don't really want to keep it in the object afterwards I'll have to more or...

Syntax Error in creating javascript constructor function

javascript,prototype,function-constructor
I am trying to create a constructer function as follows in javascript. But i get the error: SyntaxError: Unexpected token ILLEGAL I am getting this when i run the following in chrome developer tools console: function People () { ​this.superstar = "Michael Jackson"; } Is there any syntax error in...

Javascript Decorator Pattern by Addy Osmani

javascript,prototype,decorator
Given this code: // Constructor. var Interface = function (name, methods) { if (arguments.length != 2) { throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2."); } this.name = name; this.methods = []; for (var i = 0, len = methods.length; i < len;...

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...

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,...

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'); }...

someFunction.Prototype.constructor vs someFunction.constructor

javascript,constructor,prototype
I am aware of the fact that functions in JavaScript lead a dual life first of a function (as first class thing to create instances from) and the second one of a normal object. But I am surprised to see the output of the following console. function A() { console.info("A");...

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'); }...

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...

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...

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...

Javascript - Help w/ prototypes and properties?

javascript,properties,prototype
I'm currently writing a code for my javascript class and I've hit a dead end. The task is to make a "virtual pet app" that has several properties: hungry, ill, and lonely. There are also two prototypes (a dog and a fish) that share the main pet object. Here is...

BUBBLE SORT Help in C . line-based questions from a source code

c,arrays,prototype
http://www.sanfoundry.com/c-program-sorting-bubble-sort/ My questions are: At line 28: Why num - i - 1? At line 30: what does the if condition mean? especially, why j + 1? How to display the elements of the sorted array randomly? No Asc or Dsc order? How to differ in the displayed random numbers?...

The correct way to implement prototypal inheritance

javascript,oop,inheritance,prototype
There is already numerous threads about prototypal inheritance in JavaScript, but this is not a copy due to laziness. I have literally read them all and have found almost as many different syntactic approaches as I have found answers, so it appears that I am not the only one that...

Extend a JavaScript object with a default function

javascript,arrays,prototype,javascript-objects
In google app scripts I have a one dimensional data array that I can get values from like this: data[0] I'd love to be able to pass in the column name instead like this: data("A") That way I don't have to convert letters into their array position. So I'd like...

Extending prototypes in Javascript - good way?

javascript,oop,inheritance,prototype,extend
I want to validate that the approach I'm using is correct when it comes to extend a prototype - supposing "extend" is the right word. This topic gets a lot of clones. I'm still trying to properly understand this topic... The purpose is: - to write clean and good code....

Why isn't background image for second div showing?

html,css,user-interface,prototype,jsfiddle
This is the prototype I am trying to implement Here is JsFiddle of what I have so far : JS Fiddle What I am trying to do is make the options-Pick a Spending Profile, Find me suitable cards, etc have a background color. I tried doing this from the div...

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...

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."...

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...

How can I create a callable prototype method within another prototype

javascript,prototype
I'm working on trying to build a small library of functions within an object prototype. I'd perviously just been throwing my helper functions as global functions, however i'm trying to migrate to something more self contained. Anyway my proto wrapper looks like this; Q.fn = jHelper.prototype = { // helper...

Javascript Prototype method and un-used variables

javascript,node.js,prototype
I am currently building objects via prototype method. This object requires no user built methods and while a factory approach may be better here, I am more comfortable with prototyping. I am wondering about the var buf = data._raw;. What happens to buf once the object is returned, does it...

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:...

Backbone Model object has undefined prototype property during fetch [duplicate]

javascript,backbone.js,prototype
This question already has an answer here: Backbone.js collectin throw the error 1 answer I am attempting to define a Backbone collection and then use Backbone.fetch to pull data from an API. But when I run fetch on the collection, I end up getting this error: When I inspected...

Where the __proto__ is pointing when we change the prototype of the parent object?

javascript,oop,prototype
Normally when we create a new object using "new" keyword, actually the __proto__ property of the created object is pointing to the prototype property of the parent class. We can test this as below : function myfunc(){}; myfunc.prototype.name="myfunction"; var child= new myfunc(); child.__proto__=== myfunc.prototype ---> true But let's see what...

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,...

javascript chainable nested subclass

javascript,prototype,prototypal-inheritance
I'm effectively trying to build a chainable object that contains sub objects or other functions. It should be used like this: val().rules.phone("someValue"); So far: var val = function(){ var validator = function(){ this.fields = []; return this; } validator.prototype = { addField: function(fieldName){ this.fields.push(fieldName); return this; }, rules: { phone:...

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...

Javascript nested / encapsulated prototype method

javascript,oop,nested,prototype,encapsulation
Is there any way to have Object prototype methods nested within an object's definition so that it keeps best readability? The main concern is the memory footprint involved, and efficiency. It's frustrating to come from a language like C# or even see that PHP has better object implementation (In My...

Javascript method chaining definition

javascript,prototype
What is the difference between when using method chaining in Javascript I know that this can have some strange quirks so I am unsure: var Kitten = function() { this.name = 'Garfield'; this.color = 'brown'; this.gender = 'male'; }; Kitten.prototype.setName = function(name) { this.name = name; return this; }; Kitten.prototype.setColor...

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...

HTML