FAQ Database Discussion Community


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

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

C language prototype creation

c,function,prototype
I have this block of code. I have to move the given function display_name() into another .c file, compile it, and find the error that was caused due to the migration of the function and correct it by creating a header file with a prototype. How can I do it?...

Set click attribute, which calls a prototyped method in javascript constructor

javascript,click,prototype
*Although I can see the similarities, the question referenced as a duplicate is regarding binding click events to objects within objects via a callback. My question is regarding binding click events to properties of an object. So while similar, I was not able to apply the information in that question...

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

Change the value of a key in ES6 constructor

javascript,class,prototype,ecmascript-6
Question: How do I write a proper prototypical function using classes in ES6? How do I make sure that this function will change the value of title key in the constructor of Todo class? class Todo{ constructor(title){ this.title = title; } setTitle(newTitle){ this.title = newTitle; } } var a1 =...

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

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

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

Where does an object's toString method get its value from?

javascript,class,inheritance,prototype
I'm writing some custom classes in JavaScript and I would like their toString method to return a value that reflects the class itself rather than the Object class. For example: function MyClass(){} var my_object=new MyClass(); alert(my_object);// Returns "[object Object]" If I instantiate an HTMLImageElement the result is different: var my_image=new...

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

Using prototype apply vs this to call function

javascript,prototype,this
On the MDN String page they have an example to polyfill String.includes. String.prototype.includes = function() {'use strict'; return String.prototype.indexOf.apply(this, arguments) !== -1; }; Is there a reason they used String.prototype.indexOf.apply vs calling indexOf directly on this? String.prototype.includes = function(searchString, position) {'use strict'; return this.indexOf(searchString, position) !== -1; }; ...

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

How to change toString() for primitive types' implicit conversions in Javascript?

javascript,prototype
As an experiment, I did something like this: Object.prototype.toString=function(){ alert('works!'); } 'test'+{}; // alert is shown However, this doesn't work for primitives: Number.prototype.toString=function(){ alert('works!'); } 'test'+123; // no alert 'test'+(new Number(123)); // no alert (123).toString(); // yes alert Is it possible for primitive implicit conversions to use a custom toString...

What makes the object.prototype to the constructor function if he has no name? [duplicate]

javascript,function,class,inheritance,prototype
This question already has an answer here: Defining a Javascript prototype 5 answers My following code is this: var triangle = {a:1, b:2, c:3}; function constructorFunction() { this.color = "red"; } constructorFunction.prototype = triangle; I know that the prototype keyword extends classes in this syntax: Object.prototype.method = function() {}...

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

JS prototyping Cannot set property 'moveRight' of undefined

javascript,class,properties,prototype,undefined
I've a problem with this simple prototyping: Game = function (moduleConfig, gameConfig) { this.moduleConfig = moduleConfig; this.gameConfig = gameConfig; // Game-Commands this.keyCommands = { moveLeft: false, moveRight: false }; this.catcher = null; this.stage = null; return this; } /** * Left arrow down */ Game.prototype.onKeyboardLeftDown = function () { this.keyCommands.moveLeft...

Is there anything similar to JavaScript's “prototype” in Java?

java,javascript,inheritance,polymorphism,prototype
Right, so I know Java fairly well but I never studied extensively into JavaScript. I was chatting with an acquaintance who knows JavaScript, but who has not studied into Java. He was telling me about the advantages of JavaScript over Java in terms of how it functions but not its...

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

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

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

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

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

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

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

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

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

Creating functions in function prototypes for Javascript

javascript,function,prototype
How do I properly create a function within a function prototype? What I have is this: <body> <p id="demo"></p><script> function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } person.prototype.name = function() { return { myFunc: function() { this.firstName + "...

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

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

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

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

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

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

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

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

Copy Javascript “Class” Prototype to an Object

javascript,node.js,prototype
I have a created a class User. It has some properties like: name, id, password, etc. I've set up a constructor like: function User(name1, email, password) { this.name = name1; this.id = __GUID(); this.type = __TYPE; this.addNewEmail(email); this.password = (new Password).createFromRawPassword(password).crypt; } And some prototype functions like: User.prototype.save = function(cb,...

Understanding an unexpected result due to an unmatched prototype (C89)

c,prototype,c89
I have a program goo.c void foo(double); #include <stdio.h> void foo(int x){ printf ("in foo.c:: x= %d\n",x); } which is called by foo.c int main(){ double x=3.0; foo(x); } I compile and run gcc foo.c goo.c ./a.out Guess what? I get "x= 1" as result. Then I find the signature...

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

What's the difference between these 2 implementations of prototypal inheritance?

javascript,inheritance,prototype,prototypal-inheritance
What's the difference between these 2 implementations of prototypal inheritance, and considering that we're working with 2 different "prototypes" (the prototype property that's only on functions, and the internal prototype), and how do these implementations differ in their prototype chain lookup? Also, does the first implementation (using the prototype property)...

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

How to call a function and pass a variable with period notation

javascript,function,prototype
I have seen this used before but am not sure how to actually implement it. How can a pass a function a variable with this syntax foo.function() , have foo passed as the input. Ideally i would like to have it work like this var foo = 'some string'; var...

C++ constructor prototype parameter

c++,class,constructor,arguments,prototype
For example, there is a class foo : class foo { public: foo (int = 10); ..... } The prototype of the constructor has "int = 10" inside. So, what does it mean? Int is just an integer type, isn't? So, isn't that illegal to assign a value to it?...

Why does the __proto__ object evaluate to “Object” in the debugger?

javascript,debugging,prototype,google-chrome-devtools,prototypal-inheritance
I'm reading Kyle Simpson's "YDKJS: this & Object Prototypes", and looking at his example of behavior delegation. Here's the code below: Foo = { init: function(who) { this.me = who; }, identify: function() { return "I am " + this.me; } }; Bar = Object.create( Foo ); Bar.speak = function()...

Is this correct (JavaScript prototype property)?

javascript,prototype,javascript-objects
Here I created a function which will ultimately be used as a constructor for other clones. Aside from the properties arguments, caller, length, name, __proto__(link to Function.protoype) created, the prototype property is created. This property points to the object which will be assigned as the prototype to the instances created...

why is a.y undefined here?

javascript,inheritance,prototype
function A() {} A.prototype.x = 10; var a = new A(); alert(a.x); // 10 A.prototype = { x: 20, y: 30 }; alert(a.y) // undefined Why does it delegate to old prototype of a.x and not the newer one? Why is a.y throwing undefined through it is set in prototype?...

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

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

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

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

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

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

How to push objects into array inside of a JavaScript Prototype?

javascript,angularjs,prototype,angularjs-service,angularjs-factory
I have an Angular Factory whose job is to save special objects and retrieve them later. (Used to save the users workflow when he switches views). Basically I need to save objects with a name, as well as an array of tags. My problem is with the saving the tags...

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

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

JavaScript oop: Designing classes correctly

javascript,oop,closures,prototype
Taking this list of similar questions: How to set up JavaScript namespace and classes properly Javascript namespace declaration with function-prototype Best OOP approach to these two small JavaScript classes I'd concluded there are two possible ways for implementing classes and instances in JS: using an inner function or using a...

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

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

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

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

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

How to change an attribute of a javascript prototype object

javascript,object,attributes,prototype
html base <html> <head> </head> <body> <input type="text" class="abc"/> </body> </html> So I have my prototype object function AnArray(){ this.anArray=[]; } AnArray.prototype.getAnArray=function(val){ return this.anArray[val]; } AnArray.prototype.setData=function(index,val){ this.anArray[index].data=val; } var objAnArray=new AnArray(); the object ends up looking like this id: 1, pid: "questions-worth-asking", num: 1, data: null and I'm trying to...

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

Why perl $$ prototype not grab two arguments

perl,prototype
I read now http://www.perlmonks.org/?node_id=861966 But I have a question about internals What is cause that prototype sub atan2($$); not cause the parser to grab only two arguments: So @a = (atan2 1, 2, 3); does not become @a = (atan2(1, 2), 3); What is a cause to not allow perl...

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

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

JS Inheritance and mutating prototype

javascript,inheritance,prototype
AFAIK, JS provides inheriatnce by means of assigning a prototype chain to a newly created object. So, the code below seems to be the correct way to me: function Animal(name){ this.name = name; } Animal.prototype.getName = function(){return this.name;}; function Cat(){ Animal.apply(this, arguments); } Cat.prototype = Object.create(Animal.prototype); Cat.prototype.constructor = Cat; Cat.prototype.sayHi...

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

Why put methods on the prototype of a class instead of declaring them in the constructor? [duplicate]

javascript,node.js,inheritance,prototype
This question already has an answer here: Use of 'prototype' vs. 'this' in JavaScript? 10 answers I'm trying to learn more about prototypal inheritance and I'm a little confused about the difference between adding methods to the prototype and adding them to the instance. Why would I do one...

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

What does the 'this' point to in prototype method?

javascript,prototype,this
The question confuses me for a time. Here's a simple code: function A() {}; A.prototype.B=function() {return this}; A.prototype.B(); The result in chrome console is: A{}; >B: function() {}; >constructor: function A() {}; > proto: Object As I know, 'this' point to the object who called the method. So I think...

Difficulty Manually Walking The Prototype Chain

javascript,constructor,prototype
I wanted to try manually walking the prototype chain of a few objects just to see what I find along the way. However, I got stuck on the first one that I tried. Here's the code: function MyObject() { } var x = new MyObject(); console.log('--------------------------------------------'); console.log('x.constructor.name: ' + x.constructor.name);...

Make special function prototypes in javascript

javascript,function,prototype
I was thinking about this... I know that you can do Object.prototype.example() but I was wondering how to do something like this: ExampleFunction().prototype.exampleHandler. Sort of like how this works:document.querySelector().id I think that it is possible. If you have any questions about it, please comment! Thanks for helping out!...

Can I use `obj.constructor === Array` to test if object is Array?

javascript,arrays,types,prototype
Is it correct to use obj.constructor === Array to test if an object is an array as suggested here? Does it always returns correct answer compatible with Array.isArray?

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

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

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

JS Power Constructor and instanceof without new

javascript,constructor,prototype,new-operator
To quote this guy we can use a power constructor which has the form function constructor() { var that = {}; that.data = true; that.method = function () {}; return that; } To create objects that will behave correctly with or without the new keyword. My question is how do...

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

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

Issue of prototype

javascript,prototype
I have a simple issue, but i can't understand. <script type="text/javascript"> var man = function(){ var age = 1; this.shoes = 2; }; man.prototype = { create: function(){ //age = 5; console.log(age); console.log(this.shoes); } } var man1 = new man; man1.create(); </script> -Ok,I create a man with 2 vars, age...

Arrow disable if there are no more image in the left or right

jquery,ajax,prototype,bxslider
I use BxSlider carousel to display my gallery image, Lets say that I have nine images and the script is set with minSlides: 3 and maxSlides: 3, and i am watching image 1-3, then the arrow should be only on the right side, which means i can browse for more...

assigning object to prototype

javascript,node.js,prototype
I am trying to assign a object to a prototype, but I keep getting a error that the object is undefined. I am trying to do this //x.prototype.y = {}; StreetEasy.prototype.neighborhoodPaths = {}; and at a later point in the code I am trying to access this object in another...

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

I cannot keep the bean stateful when the spring bean is value = “prototype”, proxyMode = ScopedProxyMode.TARGET_CLASS

spring,proxy,prototype,javabeans
here is the spring bean: @Repository @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) public class TestBean { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } } and here is the very simple codes to access the bean: TestBean testBean =...

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

HTML