javascript - creating a public method on a constructor function: Why use the prototype keyword? - Stack Overflow

If I create a constructor function BlahWidget and give it 2 public methods: publicHello and secondHello

If I create a constructor function BlahWidget and give it 2 public methods: publicHello and secondHello. I assign publicHello directly inside the widget using 'this' but use the prototype object to assign the secondHello method, what difference does that really make to the behaviour of the 2 methods on the widget?

var BlahWidget = function(){
  this.publicHello = function(){
    alert("Hello");
  }
};

BlahWidget.prototype.secondHello = function(){
  alert("Second Hello");
}

My understanding was that using .prototype allows it to be called by inherited objects. But turns out that this is not the case. Both methods can be called by the inherited function objects, as shown below:

var MiniBlah = function(){

  this.callSupers = function(){
     this.publicHello();    
     this.secondHello();
  }
}


MiniBlah.prototype = new BlahWidget();
MiniBlah.prototype.constructor = MiniBlah;

var x = new MiniBlah();
x.callSupers();//calls both publicHello and secondHello

If I create a constructor function BlahWidget and give it 2 public methods: publicHello and secondHello. I assign publicHello directly inside the widget using 'this' but use the prototype object to assign the secondHello method, what difference does that really make to the behaviour of the 2 methods on the widget?

var BlahWidget = function(){
  this.publicHello = function(){
    alert("Hello");
  }
};

BlahWidget.prototype.secondHello = function(){
  alert("Second Hello");
}

My understanding was that using .prototype allows it to be called by inherited objects. But turns out that this is not the case. Both methods can be called by the inherited function objects, as shown below:

var MiniBlah = function(){

  this.callSupers = function(){
     this.publicHello();    
     this.secondHello();
  }
}


MiniBlah.prototype = new BlahWidget();
MiniBlah.prototype.constructor = MiniBlah;

var x = new MiniBlah();
x.callSupers();//calls both publicHello and secondHello
Share Improve this question edited Mar 4, 2011 at 20:31 Pointy 414k62 gold badges594 silver badges628 bronze badges asked Mar 4, 2011 at 20:22 uditudit 2,7833 gold badges34 silver badges45 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

The difference is that functions declared on the prototype object are shared across instances of objects created by a constructor function whereas functions declared inside of the body of a constructor function are not, they belong to the object constructed from the function.

What this means in practice is that you could create a load of objects from a constructor function with a function on the prototype doing X, then change that function on the prototype to do Y and all object instances will get the new functionality of the function.

An example

var BlahWidget = function(){
  this.publicHello = function(){
    console.log("Hello");
  }
};

BlahWidget.prototype.secondHello = function(){
  console.log("Second Hello");
}

var blah1 = new BlahWidget();

var blah2 = new BlahWidget();
blah2.publicHello = function() {
    console.log("Goodbye");
}

blah1.secondHello(); // logs SecondHello
blah2.secondHello(); // logs SecondHello

BlahWidget.prototype.secondHello = function(){
  console.log("Second Goodbye");
}

blah1.secondHello(); // logs Second Goodbye
blah2.secondHello(); // logs Second Goodbye

blah1.publicHello(); // logs Hello
blah2.publicHello(); // logs Goodbye

Every single instance of "BlahWidget" will have its own distinct copy of the "publicHello" function.

Also, though this is just academic, I'm not sure I'd say that "prototype" is a keyword; it's more like a "special property name".

In JavaScript Functions are so powerful to build OOPs and modular concepts. Following concepts are implemented using Function only in JavaScript:

  1. Method
  2. Class
  3. Constructor
  4. Module

Below code shows the code which create class MyClass and it has private members:

function MyClass(a) {  
    var count = 3; // private member  
  
    // this check function is private function  
    function check() {  
        if (count > 0) {  
            count--;  
            return true;                  
        }  
        else {  
            return false;  
        }  
    }  
    this._a = a;  
    this.get = function () {  
        if (check()) { // use of private function  
            return this._a;  
        }  
        else {  
            return "Thullu"; // after invoking get method 3 times in the object this else will be executed  
        }  
    }  
}  

In the above code variable, count is private as any object created from MyClass will not have this variable similarly function check() is private function as this function is not part of this in the MyClass. When we create an object of MyClass using new keyword this is returned. This concept is possible in JavaScript because of lexical scoping (functional scoping).

When we create object of this class MyClass, and call the get method more than 3 times:

I would like to write few points regarding new keyword.

When a function is called with the new operator, a new object is created with prototype members and assigned to this. Above statement is true only if there is no explicit return value in the function. If explicit return is present in Class (function), then same return will be assigned to the object. I would like to give here one more example with very basic functionality like in all OOP languages we have. We declare private field and then use public properties to expose the private field, in more formal and OOPs way we create Get and Set method to update private field or retrieve private member of class.

Same get and set functionality for private variables in JavaScript we can achieve as shown in below example:

// private class with get and set methods  
   function MyClass() {  
       var _privateField = 0; // It is private field as it is not part of "this"  
       this.GetPrivateField = function () {  
           return _privateField;  
       };  
       this.SetPrivateField = function (value) {  
           _privateField = value;  
       };  
   } 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742344016a4426182.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信