سؤال

please clarify the difference b/w this two codes

function Person(gender) {
        this.gender = gender;
        alert('Person instantiated');
    }

    Person.prototype.sayHello = function()
    {
        alert ('hello');
    };

    var person1 = new Person('Male');
    var person2 = new Person('Female');
 // call the Person sayHello method.
    person1.sayHello()

and the second one is below where function define inside funciton (without prototype property)

 function Animal(gender) {
        this.gender = gender;
        alert('animal instantiated');
        this.sayToodle =  function()
        {
            alert ('GOOOOOOO!!');
        };
    }



    var Animal1 = new Animal('Male');
    var Animal2 = new Animal('Female');


    Animal1.sayToodle();
my more simple question are:
  1. what is the difference?
  2. define method inside or out side of a function. what is the effect?
  3. if both same then which is the fine way to define this.
  4. and what does prototype do?

Can we not define method of a obj out side of its function(CLASS)???

هل كانت مفيدة؟

المحلول

Defining a member inside the constructor (such as: this.name) gives only that instance of the object access to that member.

Defining a member inside the prototype allows all instances to "share" that property.

A way that helped me understand this was to define an array (or any other member that is not a method) inside the prototype, like so:

function Animal() {}

Animal.prototype = {
    kids: [],
    giveBirth: function() {
        for(var i = 0; i < arguments.length; i++) {
            this.kids.push(arguments[0]);
        }
    }
}

var cat = new Animal();
var giraffe = new Animal();

cat.giveBirth('kitten','another kitten','yet another kitten');

// cat.kids === ['kitten','another kitten','yet another kitten'];
// giraffe.kids === ['kitten','another kitten','yet another kitten'];

If you notice, the giraffe's kids were set (as kittens). Why is this? Because in this case, .giveBirth() accesses the prototype's kids array, which is shared by all instances.

What if we don't want to share the members, because the members are unique? You can do like so:

function Animal() {
    this.kids = [];
}

Animal.prototype = {
    giveBirth: function() {
        for(var i = 0; i < arguments.length; i++) {
            this.kids.push(arguments[0]);
        }
    }
}

var cat = new Animal();
var giraffe = new Animal();

cat.giveBirth('kitten');

// cat.kids === ['kitten']
// giraffe.kids == undefined

giraffe.giveBirth('baby giraffe');

// cat.kids === ['kitten']
// giraffe.kids === ['baby giraffe']

As you pointed out in the comments, part of how you decide to define the properties plays into memory usage; another part plays into what members you want to be "shared" across all instances.

To get a little more insight into prototypes (through understanding how new works), see What is the 'new' keyword in JavaScript?, on StackOverflow.

Here's a quote from there:

After a lot of searching, I have finally found out exactly what the new keyword does, and it is 4 things:

  1. It creates a new object. The type of this object, is simply object.
  2. It sets this new object's internal, inaccessible, [[prototype]] property to be the constructor function's external, accessible, prototype object.
  3. It executes the constructor function, using the newly created object whenever this is mentioned.
  4. It returns the newly created object, unless the constructor function returns a non-primitive value. In this case, that non-primitive value will be returned.

نصائح أخرى

Prototype members are shared among instances and members in the constructor function defined as this.something are instance specific.

When an instance need instance specific members (like Person.name) define it as this.name. When it can be shared (like a method sayName) define it on the prototype like: Person.prototype.sayName=function(){...

For more info on prototype and constructor functions you can check this answer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top