原文地址:JavaScript Object浅谈

Introduction

学习对JavaScript的Object进行操作。

JavaScript

Script 1

Create an object Constructor to create an object of a book. Make sure you have 5 different properties like title, author, publish date, edition, etc. Next, write the script that adds a new book to the array and finally uses "document.write" to print the object to the web page.

Script 2

Using the example script from the lesson (see below), extend the script so that it loops through each of the programming languages in the object array. Print out all of the properties for each object. And if the object's name contains javascript, output a special message.

function progLangObj(name,use,level,status) {
  this.name=name;
  this.use=use;
  this.level=level;
  this.status=status;
  this.addToArray = function() {
    theProgLangArray.push(this);
  };
  this.addToArray();
}

// Initialize the array, and create some objects ...
var theProgLangArray = [];
var oJavascript = new progLangObj("JavaScript","Client Side Scripting","Easy","Fun");
var oPHP = new progLangObj("PHP","Server Side Scripting","Medium","Also Fun");
var oJava = new progLangObj("Java","Compiled Language","Hard","Fun but hard!");

// Create a loop that can loop through the entire theProgLangArray array and print out the name, use, level and status contained in each object.
// your code here
// Hint: think of this as two loops ... one loop to loop through each object in the array, and an inner loop that prints out the items in the object.

Objects, everywhere

Everything in JavaScript is an Object: a String, a Number, an Array, a Date.... In JavaScript, an object is data, with properties and methods.

An object is a self-contained entity comprising of 'properties' (think variables) and methods (functions that do something with the variables typically). The object stores data in the properties and can perform tasks via the methods. You use objects all the time as you program in JavaScript.

There are built in objects like Date and Math, and the browsers' Document Object Model (the web page itself). Don't worry about that last piece about the DOM yet, more on this to come soon enough.

Finally, there are objects that you make that are used by your programs.

When you create an object, it uses an approach called prototyping. Simply, this means that you are declaring an object with name and then adding the properties to it (which are basically variables). Then, anytime you need a new instance of this object, you instantiate it by calling with a new keyword.

How about we create an object for JavaScript as a language? Here we go:

progLangObj = new Object();
progLangObj.name = "JavaScript";
progLangObj.use = "Client side scripting";
progLangObj.level = "Easy"
progLangObj.status = "Fun"

We just created an object called "progLangObj" and added the following properties to it: "name", "use", "level", and "status".

Note, you can also build an object like this:

var progLangObj = {name:"Javasctript", use:"Client Side Scripting", level:"Easy", status:"Fun"};

Now let's do something with this object, we'll start by outputting the properties of the object to the screen:

alert(progLangObj.name + " is " + progLangObj.level);

If you run that statement, you will see one of the values stored in our programming object that we created above.

You may be wondering, one value is nice, but how can I see everything in my object? Here is a way to loop through all of the properties and values of the progLangObj object:

for (var prop in progLangObj) {
  document.write(prop + " = " + progLangObj[prop]);
}

Object Constructor

The next step in using objects is to re-use it. An object is like, well, a thing that we can use again and again. The object can be a template - or a class - and like a function where you are able to feed different parameters in code and use it again and again, we can now use a function to create and name an object that you can then add properties to and access throughout a script. To do this, we use an object Constructor, which is a function that you define in order to create multiple objects of a similar type ... like this:

function progLangObj(name,use,level,status) {
  this.name=name;
  this.use=use;
  this.level=level;
  this.status=status;
}

Now, every time you want to store information about a new programming language that you know about, you can instantiate a new progLangObj like this:

var oJavascript = new progLangObj("JavaScript","Client Side Scripting","Easy","Fun");

and then

var oPHP = new progLangObj("PHP","Server Side Scripting","Medium","Super Fun");

Now, let's look again at how you can loop through the object and find it's properties.

The code below, is how this loop is set up, it will not run as is. Just look at it to see how we are looping through all of the properties of an object and for each, printing out the property name and value. Note how the object's key and value pairs are separated by simply declaring the variable name (property) and the object.

for (var property in objectname) {
  alert(property+ " = " + objectname[property]);
}

So, here is the full script, this will run, it will create the object construction class add then add a programming language object, and finally print it out:

function progLangObj(name,use,level,status) {
  this.name=name;
  this.use=use;
  this.level=level;
  this.status=status;
}
var oJavascript = new progLangObj("JavaScript","Client Side Scripting","Easy","Fun");
for (var prop in oJavascript) {
  alert(prop + " = " + oJavascript [prop]);
}

I assume you are now thinking "ok, that's great, but how do I loop through all of my objects without knowing it's name? Is there an object of all my objects?" Well, no, but you can create an array that holds the names of all your objects, and the best way to do this is by adding it to the constructor. However, we need to talk about "this" first.

THIS

"This" is a keyword that you'll see in Javascript when working with objects. It refers to the element or object that you are currently working on and can be quite a powerful tool in a function. For example, you can pass the element or object in to the function and do things to it without having to specify by name exactly which object you are working on!

So, in the object Constructor class above I threw a "this" into the mix without explanation. In the following example note that "this" refers to the object that progLangObj is making:

function progLangObj(name,use,level,status) {
  this.name=name;
  this.use=use;
  this.level=level;
  this.status=status;
}

When we call on the function, it instantiates an object and assigns the name, use, etc. by using "this" as the placeholder for the objects name.

Next, I'm using the "push" method to push the new object in an array that contains all of my objects.

function progLangObj(name,use,level,status) {
  this.name=name;
  this.use=use;
  this.level=level;
  this.status=status;
// with the following function, I am creating a function called "addToArray" that expects an object and will append (or push) it into the array
  this.addToArray = function() {
    theProgLangArray.push(this);
  };
  this.addToArray();
}
// Now, we get to work by initializing the array, and creating some objects ...
var theProgLangArray = [];
var oJavascript = new progLangObj("JavaScript","Client Side Scripting","Easy","Fun");
var oPHP = new progLangObj("PHP","Server Side Scripting","Medium","Also Fun");
var oJava = new progLangObj("Java","Compiled Language","Hard","Fun but hard!");

Ok, now we're set up ... we've created the array, we've created objects, and as we were creating each object, we pushed the object into an array that we can now use to call up all of our objects. Here is the final step, a loop to go through the array. Let's use the forEach method to loop:

theProgLangArray.forEach(function(language) {
  var x = language.name
  alert(x);
});

Pretty interesting, right? Now, can you figure out how to also show the use, status, and level of the progLangObj?

Next steps

Read up on objects:

Ok ... let that all sink in and then head over to the Assignments section and look for Assignment 6.

(本文出自csprojectedu.com,转载请注明出处)


csprojectedu
751 声望201 粉丝

Microsoft, ACMer, 现BAT全栈工程师。