EzDevInfo.com

prototype

Prototype JavaScript framework Prototype JavaScript framework: a foundation for ambitious web applications

What is the reason to use the 'new' keyword at Derived.prototype = new Base

What does the following code do:

WeatherWidget.prototype = new Widget;

where Widget is a constructor, and I want to extend the Widget 'class' with a new function WeatherWidget.

What is the new keyword doing there and what would happen if it is left out?


Source: (StackOverflow)

Understanding the difference between Object.create() and new SomeFunction()

I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with 'new SomeFunction()', and when you would want to use one over the other.

Consider the following example:

var test = {val: 1, func: function(){ return this.val; }};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function(){
    this.val = 1;
    this.func = function(){
        return this.val;
    };
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB .val = 2;
console.log(otherTestA.val); // 1 
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2

Notice that the same behavior is observed in both cases. It seems to me that the primary differences between these two scenarios are:

  • The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.
  • You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Are the above statements correct? And am I missing something? When would you use one over the other?

EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/


Source: (StackOverflow)

Advertisements

Advantages of using prototype, vs defining methods straight in the constructor? [duplicate]

This question already has an answer here:

I am wondering if there are any advantages of using any of these over the other, and which way should I go?

Constructor approach:

var Class = function () {

    this.calc = function (a, b) {
        return a + b;
    };

};

Prototype approach:

var Class = function () {};

Class.prototype.calc = function (a, b) {
    return a + b;
};

I don't like that, using the prototype, method definitions are separated from the class, and I'm not aware if there is any specific reason I should use this over just the first approach.

Also, is there any benefit of using a function literal to define a "class", over just function definition:

var Class = function () {};

vs

function Class () {};

Thanks!


Source: (StackOverflow)

Why are Perl 5's function prototypes bad?

In another question a member asserted "I would advice you not to use prototypes. They have their uses, but not for most cases and definitely not in this one."

Can anyone elaborate on why this might be true (or otherwise)? I almost always supply prototypes for my Perl functions, and I've never before seen anyone else say anything bad about using them.


Source: (StackOverflow)

JavaScript: What are .extend and .prototype used for?

I am relatively new to JavaScript and keep seeing .extend and .prototype in third party libraries I am using. I thought it had to do with the Prototype javascript library, but I am beginning to think that is not the case. What are these used for?


Source: (StackOverflow)

Calling base method using JavaScript prototype

Is it possible to call the base method from a prototype method in JavaScript if it's been overridden?

MyClass = function(name){
    this.name = name;
    this.do = function() {
        //do somthing 
    }
};

MyClass.prototype.do = function() {  
    if (this.name === 'something') {
        //do something new
    } else {
        //CALL BASE METHOD
    }
};

Source: (StackOverflow)

What can the JavaScript prototype system do beyond mimicking a classical class system?

The prototype system looks much more flexible than the traditional class system, but people seem to feel content with the so-called "best practices", which mimic the traditional class system:

function foo() {
  // define instance properties here
}

foo.prototype.method = //define instance method here

new foo()

There must be other things that a prototypal system can do with all the flexibility.

Are there uses for a prototypal system outside of mimicking classes? What kinds of things can prototypes do which classes cannot, or are there none?


Source: (StackOverflow)

What it the significance of the Javascript constructor property?

Trying to bend by head around Javascript's take on OO...and, like many others, running into confusion about the constructor property. In particular, the significance of the constructor property, as I can't seem to make it have any effect. E.g.:

function Foo(age) {
    this.age = age;
}

function Bar() {
    this.name = "baz"; 
}

Bar.prototype = new Foo(42); 
var b = new Bar;    

alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name);        // "baz". Shows that Bar() was called as constructor.
alert(b.age);         // "42", inherited from `Foo`.

In the above example, the object b seems to have had the right constructor called (Bar) – and it inherits the age property from Foo. So why do many people suggest this as a necessary step:

Bar.prototype.constructor = Bar;

Clearly, the right Bar constructor was called when constructing b, so what impact does this prototype property have? I am curious to know what practical difference it actually makes to have the constructor property set 'correctly'—as I can't see it having any affect on which constructor is actually called after an object is created.


Source: (StackOverflow)

Multiple inheritance/prototypes in JavaScript

I've come to a point where I need to have some sort of rudimentary multiple inheritance happening in JavaScript. I'm not here to discuss whether this is a good idea or not, so please keep those comments to yourself.

I just want to know if anyone's attempted this with any (or not) success, and how they went about it.

To boil it down, what I really need is to be able to have an object capable of inheriting a property from more than one prototype chain (i.e. each prototype could have its own proper chain), but in a given order of precedence (it will search the chains in order for the first definition).

To demonstrate how this is theoretically possible, it could be achieved by attaching the secondary chain onto the end of the primary chain, but this would affect all instances of any of those previous prototypes and that's not what I want.

Thoughts?

Edit Appreciate the responses folks, but while the consensus seems to be statically copying over the properties from both trees, which would work in most cases (and will probably be what I end up doing), I was most interested in a dynamic solution that would allow the separate prototype chains to be altered, and still have those changes "picked up" by the instance.


Source: (StackOverflow)

Javascript object extending -

I am currently transforming from Java to Javascript, and it's a bit hard for me to figure out how to extend objects the way I want it to do.

I've seen several people on the internet, which has a method on object called extend. The code will look like this:

var Person = {
   name : 'Blank',
   age  : 22
}

var Robot = Person.extend({
   name : 'Robo',
   age  : 4
)}

var robot = new Robot();
alert(robot.name); //Should return 'Robo'

Does anyone know how to make this work? I've heard that you need to write

Object.prototype.extend = function(...);

But I don't know how to make this system work. If it is not possible, please show me another alternative that extends an object.


Source: (StackOverflow)

JavaScript check if anonymous object has a method

How can I check if an anonymous object that was created as such:

var myObj = { 
              prop1: 'no',
              prop2: function () { return false; }
            }

does indeed have a prop2 defined?

prop2 will always be defined as a function, but for some objects it is not required and will not be defined.

I tried what was suggested here: http://stackoverflow.com/questions/595766/how-to-determine-if-native-javascript-object-has-a-property-method but I don't think it works for anonymous objects .


Source: (StackOverflow)

C# - How to access internal class from external assembly

Having an assembly which I cannot modify (vendor-supplied) which have a method returning an object type but is really of an internal type.

How can I access the fields and/or methods of the object from my assembly?

Keep in mind that I cannot modify the vendor-supplied assembly.

In essence, here's what I have:

From vendor:

internal class InternalClass
  public string test;
end class

public class Vendor
  private InternalClass _internal;
  public object Tag {get{return _internal;}}
end class

From my assembly using the vendor assembly.

public class MyClass
{
  public void AccessTest()
  {
    Vendor vendor = new Vendor();
    object value = vendor.Tag;
    // Here I want to access InternalClass.test
  }
}

Source: (StackOverflow)

Suggested platform/tools for rapid game development and game prototyping [closed]

What platforms and tools should I use for rapid game development and prototyping?

Say that I have an idea for a simple game or a game mechanic that I want to try out, what are the best tools for quickly creating something playable that I can experiment with to try out the idea?

The platform does not necessarily have to be easy to learn, that is not the issue, but once learned it has to be quick to use.


Source: (StackOverflow)

Prototypical inheritance - writing up [duplicate]

So I have these 2 examples, from javascript.info:

Example 1:

var animal = {
  eat: function() {
    alert( "I'm full" )
    this.full = true
  }
}

var rabbit = {
  jump: function() { /* something */ }
}

rabbit.__proto__ = animal 

rabbit.eat() 

Example 2:

function Hamster() {  }
Hamster.prototype = {
  food: [],
  found: function(something) {
    this.food.push(something)
  }
}

// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()

speedy.found("apple")
speedy.found("orange")

alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)

Start from Example 2: when the code reaches speedy.found, it finds no found property in speedy, and so it climbs up to the prototype and changes it there. That's why food.length is equal for both hamsters, in other words they have the same stomach.

From this I understand, that when writing up and adding a new property which doesn't exist, the interpreter will go up the prototype chain until it finds the property, and THEN change it.

BUT in Example 1 something else happens:
we run rabbit.eat, which changes rabbit.full. full property is nowhere to be found, so it should go up the prototype chain to (to object??), and well, I'm not sure what happens here. In this example the property full of rabbit is created and changed, while in the first example it goes up the prototype chain because it cannot find the property.

I'm confused and cannot see why this happens.


Source: (StackOverflow)

Native way to merge objects in Javascript

Javascript's Object doesn't have any native merge operation. If you have two objects, say

{a:1, b:2}
{c:3, d:4}

And want to get

{a:1, b:2, c:3, d:4}

As far as I know, you have to iterate through the objects. That is to say that you decide on either a merge left or merge right strategy and then you do something like (simplified)

for (key in object2) {
  object1[key] = object2[key];
}

This is fine. However, Javascript has the call and prototype feature. For instance, turning arguments into an Array can be done with

Array.prototype.slice.call(arguments)

This approach exploits existing native code, and so therefore is less susceptible to programmer folly and should run faster than a non-native implementation.

The question

Is there a trick to use this prototype/call pattern on perhaps the Attribute or Node traversal features of the DOM, or perhaps some of the generic String functions in order to do a native object merge?

The code would look something like this:

var merged = somethingrandom.obscuremethod.call(object1, object2)

And as a result, you'd get a native merge without a traversal.

A possible, sub-optimal solution

If you could use the constructor property of an Object and then coerce one object to have a constructor of another object and then run new over the composite object, you may get a merge for free. But I don't have a firm grasp of the full implications of the constructor feature in javascript to make this call.

Lemma

The same question holds true for Arrays. A common problem is to take, say 7 arrays of numbers, then try to find out the intersection of those arrays. That is to say, which numbers exist in all 7 arrays.

You could concat them together, then do a sort, and then do a traversal, surely. But it would be nice if there is a generic intersect tucked away somewhere that we can coerce an array to doing natively.

Any thoughts?

edit:

Getting half way there

For the array problem, you could do the following:

array.concat(a, b, c).sort().join(':') and then use some tricky RegExp capture and repeat patterns in order to traverse. RegExp implementations, if you don't know, run on a very simple stack-based virtual machine. When you initialize your regular expression that's really a program that gets compiled (RegExp.compile is a deprecated JS method). Then the native runs over the string in a blisteringly fast way. Perhaps you could exploit that for membership thresholds and get better performance...

It still doesn't go all the way though.


Source: (StackOverflow)