开发者

how do i namespace pseudo-classical javascript

开发者 https://www.devze.com 2023-01-10 15:23 出处:网络
I have some simple OO code I\'ve written that I\'m playing with: //define a c开发者_如何学JAVAonstructor function

I have some simple OO code I've written that I'm playing with:

//define a c开发者_如何学JAVAonstructor function
function person(name, sex) {
    this.name = name;
    this.sex = sex;

} 

//now define some instance methods
person.prototype.returnName = function() {
    alert(this.name);
}

person.prototype.returnSex = function() {
    return this.sex;
}

person.prototype.talk = function(sentence) {
    return this.name + ' says ' + sentence;
}

//another constructor
function worker(name, sex, job, skills) {
    this.name = name;
    this.sex = sex;
    this.job = job;
    this.skills = skills;
}

//now for some inheritance - inherit only the reusable methods in the person prototype
//Use a temporary constructor to stop any child overwriting the parent prototype 

var f = function() {};
f.prototype = person.prototype;
worker.prototype = new f();
worker.prototype.constructor = worker;

var person = new person('james', 'male');
person.returnName();
var hrTeamMember = new worker('kate', 'female', 'human resources', 'talking');
hrTeamMember.returnName();
alert(hrTeamMember.talk('I like to take a lot'));

Now this is all well and good. But I'm confused. I want to include namespacing as part of my code writing practice. How can I namespace the above code. As it is now I have 2 functions defined in the global namespace.

The only way I can think to do this is to switch to object literal syntax. But then how do I implement the pseudo-classical style above with object literals.


You could for example do following:

var YourObject;
if (!YourObject) {
  YourObject = {};

  YourObject.Person = function(name, sex) {
    // ...
  } 

  YourObject.Person.prototype.returnName = function() {
    // ...
  }

  // ...
}


You don't have to use object literals, at least, not exclusively.

  1. Decide on the single global symbol you'd like to use.
  2. Do all your declaration work in an anonymous function, and explicitly attach "public" methods as desired to your global object:

    (function(global) {
       // all that stuff
    
       global.elduderino = {};
       global.elduderino.person = person;
       global.elduderino.worker = worker;
    })(this);
    

I may not be completely understanding the nuances of your issue here, but the point I'm trying to make is that Javascript makes it possible for you to start with your symbols being "hidden" as locals in a function, but they can be selectively "exported" in various ways.

0

精彩评论

暂无评论...
验证码 换一张
取 消