SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard
    Join Date
    Jan 2005
    Location
    blahblahblah
    Posts
    1,447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    make a variable available to methods within an object

    Hello,

    In PHP you would do something like this:

    PHP Code:

    class Foo
    {

      protected 
    $zar;
      protected 
    $bar;

      public function 
    setZar($someValue
      {

        
    $this->$zar $someValue;

      }

      public function 
    setBar($someValue
      {

        
    $this->$bar $someValue;

      }
      public function 
    myMethodWhereEverythingHappens() 
      {

        if ( 
    $this->zar == $this->bar) {
            
    //...
        
    }

      }
      

    Would it be correct to do the following in JS?

    Code:
    var Foo = {
    
      zar: '',
      bar: '',
    
      setZar: function(someValue){
        this.zar = someValue;
      },
    
      setBar: function(someValue){
        this.bar = someValue;
      },
    
      myMethodWhereEverythingHappens: function() {
        if(this.zar == this.bar) {
            //do something
        }
      },
    
    
    }
    Would that be correct? What's the js pattern for dealing with that kind of OO considerations?


  2. #2
    Under Construction silver trophybronze trophy AussieJohn's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    776
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    That's one way of doing it. Scoping is a little less rigid in JS, a lot of it is by convention (e.g. prepend vars with an underscore to denote they're private)

    One of the other ways to do this would be to create a function object.

    e.g. something along the lines of:

    Code javascript:
    function Foo() {
     
     
        var that = this; //for scope resolution
     
        this._zar = '';
        this._bar = '';
     
        this.baz = ''
     
        this.setBar = function(val) {
            this._bar = val;
        }
     
        this.someMethod = function() {
            //do stuff
        }
     
     
    }
     
     
    var fooey = new Foo();

    See: http://snipt.net/geekyjohn/basic-ins...bject-example/
    var details = {
    . . web: "afterlight.com.au",
    . . photos: "jvdl.id.au",
    . . psa: "usethelatestversion.com"
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •