JavaScript 面向对象15分钟教程

pgw6

贡献于2012-12-05

字数:0 关键词: JavaScript开发 Java JavaScript

本指南可以很快让你学会写优美的面向对象JavaScript代码,我保证!学会写简洁的JavaScript代码对一个开发 者的发展很重要,随着像Node.js这类技术的出现,你现在可以在服务器端写JavaScript代码了,你甚至可以用 JavaScript来查询像MongoDB这样的持久性数据存储。 现在开始写面向对象的JS(OO JS),如果你有什么问题或我遗漏了什么,在下面评论出告诉我。 Literal Notation Literal Notation只是在JavaScript中创建对象的一种方法,是的,方法不止这一种。当你打算创建一个对象实例的时候Literal Notation 是首选的方法。 上面的代码没太大用处,仅仅只是创建了一个空对象。让我们动态的添加一些属性和方法到这个对象。 这里我们添加了“name”属性并赋值为“Bill E Goat”。我们不一定要在前面创建空对象,还可以只用一步完成 上面 所有的事。 很简洁漂亮是不是?访问属性和方法也一样很简单。 如果属性名不是一个有效的标识符我们还可以这么访问它: 请注意当调用一个方法时我们要在方法名后面添加一对括号去调用它。让我们重写当前的sound方法并传给它 一个参数来调用它: 很好,我们传入了一个参数(noise),并且在方法的内部访问了它。下面我们继续添加一个方法来访问name属 1 varbill = {}; 1bill.name = "Bill E Goat"; 2bill.sound = function() { 3 console.log( 'bahhh!'); 4}; 1 varbill = { 2name: "Bill E Goat", 3sound: function() { 4 console.log( 'bahhh!'); 5} 6}; 1bill.name; // "Bill E Goat" 2bill.sound(); // "bahhh" 1bill['name']; // "Bill E Goat" 1bill.sound = function(noise) { 2 console.log( noise); 3}; 4bill.sound("brrr!"); // "brrr!" He's cold :) 第 1 页/共 4 页 性: 我们可以通过this.propertyName在一个方法内部访问属性 这些代码会有什么结果。我们不使用括号调用sayName,它返回了一个方法定义。继续探索! 我们把一个叫sound的本地方法赋值给一个对象sound,现在可以在sound后面添加括号并传入参数调用那个方 法了。如果我们试着克隆Bill会有什么结果? 在上面的例子中我们创建了一个新的变量sally,并让它和bill相等。现在sally和bill在内存中引用同样的对象。 对一个对象的改变会影响到另一个。 下面再看另外一个例子: bill的name属性是一个本地变量,sayName方法是在全局范围内创建的,所以this.name会在全局范围内查找 name的值。但问题是name没有定义。让我们来定义一个全局变量name看看会发生什么: 在这里我们创建了一个全局变量name,并赋值“Bearded Octo”。当我们调用sayName方法时它在全局范围内查 找name并访问到了值“Bearded Octo”,很好。下面看看Constructor Notation。 Constructor Notation 1bill.sayName = function() { 2 console.log( "Hello "+ this.name ); 3}; 4bill.sayName(); // "Hello Bill E Goat" 1bill.sayName; // function 1 varsound = bill.sound; 2sound('moo!'); // "moo!" 1 varsally = bill; 2sally.name; // "Bill E Goat", But her name is Sally silly 3sally.name = "Sally"; 4sally.name; // "Sally", Better 5bill.name; // "Sally", Oh no what happened to Bill 1bill.name = "Bill E Goat"; 2bill.sayName(); // "Hello Bill E Goat"; 3 varsayName = bill.sayName; 4sayName; // function, OK so far so good 5sayName(); // "Hello ", huh why didn't it print out Bills name? 1 varname = "Bearded Octo"; 2sayName(); // "Hello Bearded Octo" 第 2 页/共 4 页 Constructor Notation是另外一种写面向对象JavaScript的方法。当你需要为一个对象设置初始属性值和方法或者打算创建一个对象的不 同实例但他们的属性和方法都是不同的,这时首选Constructor Notation方式。下面从创建一个空对象开始: 请注意习惯上第一个字母大写来表示它是一个类。我们来用这个类创建新的对象: 我们的对象现在有自己的属性了!当创建对象时,我们可以在属性中传值进去,或者在后面修改。 第二行可能有点难理解。我们使用了一个三元操作符,它只是一种可以把if else语句块写到一行的方法。他等 价于下面的: 如果这个对象创建的时候传入了title参数,对象的title属性就会被设置。如果没有传入,会被设置成默认 值””。 我们可以创建一个方法来访问这个属性: 1 functionGame() {}; 1 varzelda = newGame(); 2 varsmb = newGame(); 3zelda.title = "Legend of Zelda"; 4smb.title = "Super Mario Brothers"; 5zelda.title; // "Legend of Zelda" 6smb.title; // "Super Mario Brothers" 1 functionGame(title) { 2 this.title = typeoftitle !== 'undefined'? title : ""; 3}; 4 varzelda = newGame("Legend of Zelda"); 5zelda.title; // "Legend of Zelda" 6zelda.title = "Ocarina of Time"; 7zelda.title; // "Ocarina of Time" 8 varblank = newGame(); 9blank.title; // "" 1 if(typeoftitle !== 'undefined') { 2 this.title = title; 3 } else{ 4 this.title = ""; 5} 6// Is the same as 7 this.title = typeoftitle !== 'undefined'? title : ""; 1zelda.loveTitle = function() { 2 console.log( "I love "+ this.title ); 3}; 4zelda.loveTitle(); // "I love Ocarina of Time" 第 3 页/共 4 页 那样看起来很整齐,但是还可以更好。我们可以给Game类添加一个方法让所有从Game类创建的对象都有这个 方法: 结语 我希望这个教程对你学习JavaScript面向对象有用。JavaScript面向对象还有很多方面,以后的教程会再作介 绍。如果有什么问题,请在下面留下评论。感谢您的阅读! 1Game.prototype.heartIt = function() { 2 console.log( "I heart "+ this.title ); 3}; 4zelda.heartIt(); // "I heart Ocarina of Time" 5smb.heartIt(); // "I heart Super Mario Brothers" 第 4 页/共 4 页 Properties, methods, and the elusive this oh my what’s a developer to do? Read this guide to writing elegant object oriented (OO) JavaScript I respond! Learning to write elegant JavaScript is important to your career as a developer. With the advent of technologies such as Node.js you can now write JavaScript on the server side, likewise you can even use JavaScript to query a persistent data store like MongoDB. So let’s get started writing some OO JS. If you have any questions or I missed something please leave me a message in the comments. Literal Notation Literal notation is just one way of creating an object in JavaScript, yes there’s more than one. Literal notation is the preferred method when you only plan on creating one instance of an object. var bill = {}; The above code isn’t very useful, it’s just an empty object. Let’s dynamically add some properties and methods to this object. bill.name = "Bill E Goat"; bill.sound = function() { console.log( 'bahhh!' ); }; Here we add the property “name” and assigned it the value “Bill E Goat”. We also gave bill our billy goat the ability bahhh. We didn’t have to create an empty object first though, we could have done it all in one fell swoop with literal notation. var bill = { name: "Bill E Goat", sound: function() { console.log( 'bahhh!' ); } }; Beautiful isn’t it? Accessing properties and methods is a breeze as well. bill.name; //"Bill E Goat"bill.sound(); //"bahhh" If our property name isn’t a valid identifier we can also access it like this. bill['name']; // "Bill E Goat" Notice that when calling a method we append parenthesis to the method name to call it. Let’s override our current sound method and pass in a parameter in the process. bill.sound = function(noise) { console.log( noise); }; bill.sound("brrr!"); // "brrr!" He's cold :) Awesome, we passed in a parameter (noise), and accessed it from inside our function definition. Now we’re rolling, next let’s add an additional method to our object that accesses the name property. bill.sayName = function() { console.log( "Hello " + this.name ); }; bill.sayName(); // "Hello Bill E Goat" We can access properties from inside a method using the notation this.propertyName so in our case this.name. bill.sayName; // function Whoa what happened there. We called the sayName method w/ out the parenthesis and it returned a function defintion. Let’s dig digger. var sound = bill.sound; sound('moo!'); // "moo!" Well that’s pretty sweet, we assigned our objects sound method definition to a local function named sound. We can than call that function by applying parentheses and passing a parameter. What do you think happens when we try cloning Bill (remember how things worked out for poor Dolly)? varsally = bill; sally.name; //"Bill E Goat", ButhernameisSallysillysally.name = "Sally"; sally.name; //"Sally", Betterbill.name; //"Sally", Ohnowhathappened In the example above we create a new variable sally, and make it equal to bill. Both sally and bill now reference the same object in memory. Changes made via one affect both of them. Rest assured though a solution to our problem exists w/ Constructor Notation. Before digging into Constructor Notation though let ’s look at one more potential gotcha w/ Object Literals. bill.name = "Bill E Goat"; bill.sayName(); // "Hello Bill E Goat";var sayName = bill.sayName; sayName; // function, OK so far so good sayName(); // "Hello ", huh why didn't it print out Bills name? Bill’s name is a local instance variable, as such it’s only available to well, Bill. Specifically the sayName function was created in the global scope, so when it came across the statement this.name it looked in the global scope for the value of name. The only problem is name isn’t defined at this point so we’re left w/ “Hello “. Let’s define name in the global scope and watch what happens. var name = "Bearded Octo"; sayName(); // "Hello Bearded Octo" Here we create a name variable in the global scope, and assign it the value “Bearded Octo”. When we call our sayName function it looks in the global scope for name and accesses the value “Bearded Octo”. Beautiful. The problem remains though. How can we create a ‘class’ upon which to base the construction of multiple objects? Constructor Notation Constructor notation is another of way writing OO JavaScript. Constructor notation is preferred when you need to set initial properties, and methods on an object or you plan on creating multiple instances of an object where the properties, and methods of each instance need to be unique. Let’s create an empty object to get us started. functionGame() {}; Notice the convention of capitalizing the first letter to distinguish it as a class. We can use this class to build new objects. var zelda = new Game(); var smb = new Game(); zelda.title = "Legend of Zelda"; smb.title = "Super Mario Brothers"; zelda.title; // "Legend of Zelda" smb.title; // "Super Mario Brothers" Our objects maintain their own properties now! When creating objects we can even pass in properties, and change those properties later. functionGame(title) {this.title = typeof title !== 'undefined' ? title : ""; }; var zelda = new Game("Legend of Zelda"); zelda.title; // "Legend of Zelda" zelda.title = "Ocarina of Time" The second line might be confusing. We’re using the ternary operator which is just a way of putting an if else block on one line. It’s equivalent in a standard if else block is noted below. if (typeof title !== 'undefined') { this.title = title; } else { this.title = ""; } // Is the same as this.title = typeof title !== 'undefined' ? title : ""; If a title parameter is passed in when the object is created, the title instance variable is assigned the value of title. If no title is passed in the title instance variable is assigned a default value of “”. We can create a method to access this property as well. zelda.loveTitle = function() { console.log( "I love " + this.title ); }; zelda.loveTitle(); // "I love Ocarina of Time" Well that’s kind of neat, but we can do better. We can add a method to the Game class that will be available to all objects created from the Game class. Game.prototype.heartIt = function() { console.log( "I heart " + this.title ); }; zelda.heartIt(); // "I heart Ocarina of Time" smb.heartIt(); // "I heart Super Mario Brothers" Conclusion I hope this tutorial proved useful in introducing you to OO JS. There are still many aspects of OO JS to cover, which I hope to go over in a future tutorial. If there is anything in particular you ’d like me to cover please note it in the comments. Thank you for reading :). 第 1 页/共 1 页

下载文档,方便阅读与编辑

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 5 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档

相关文档