本指南可以很快让你学会写优美的面向对象JavaScript代码,我保证!学会写简洁的JavaScript代码对一个开发者的发展很重要,随着像Node.js这类技术的出现,你现在可以在服务器端写JavaScript代码了,你甚至可以用JavaScript来查询像MongoDB这样的持久性数据存储。 现在开始写面向对象的JS(OO JS),如果你有什么问题或我遗漏了什么,在下面评论出告诉我。 Literal NotationLiteral Notation只是在JavaScript中创建对象的一种方法,是的,方法不止这一种。当你打算创建一个对象实例的时候Literal Notation是首选的方法。var bill = {}; bill.name = "Bill E Goat"; bill.sound = function() { console.log( 'bahhh!' ); }; var bill = { name: "Bill E Goat", sound: function() { console.log( 'bahhh!' ); } }; bill.name; // "Bill E Goat" bill.sound(); // "bahhh" bill['name']; // "Bill E Goat" 请注意当调用一个方法时我们要在方法名后面添加一对括号去调用它。让我们重写当前的sound方法并传给它一个参数来调用它: bill.sound = function(noise) { console.log( noise); }; bill.sound("brrr!"); // "brrr!" He's cold :) bill.sayName = function() { console.log( "Hello " + this.name ); }; bill.sayName(); // "Hello Bill E Goat" bill.sayName; // function 这些代码会有什么结果。我们不使用括号调用sayName,它返回了一个方法定义。继续探索! var sound = bill.sound; sound('moo!'); // "moo!" var sally = bill; sally.name; // "Bill E Goat", But her name is Sally silly sally.name = "Sally"; sally.name; // "Sally", Better bill.name; // "Sally", Oh no what happened to Bill 在上面的例子中我们创建了一个新的变量sally,并让它和bill相等。现在sally和bill在内存中引用同样的对象。对一个对象的改变会影响到另一个。 下面再看另外一个例子: 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? var name = "Bearded Octo"; sayName(); // "Hello Bearded Octo" 在这里我们创建了一个全局变量name,并赋值“Bearded Octo”。当我们调用sayName方法时它在全局范围内查找name并访问到了值“Bearded Octo”,很好。下面看看Constructor Notation。 Constructor NotationConstructor Notation是另外一种写面向对象JavaScript的方法。当你需要为一个对象设置初始属性值和方法或者打算创建一个对象的不同实例但他们的属性和方法都是不同的,这时首选Constructor Notation方式。下面从创建一个空对象开始:function Game() {}; 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" function Game(title) { this.title = typeof title !== 'undefined' ? title : ""; }; var zelda = new Game("Legend of Zelda"); zelda.title; // "Legend of Zelda" zelda.title = "Ocarina of Time"; zelda.title; // "Ocarina of Time" var blank = new Game(); blank.title; // "" if (typeof title !== 'undefined') { this.title = title; } else { this.title = ""; } // Is the same as this.title = typeof title !== 'undefined' ? title : ""; 如果这个对象创建的时候传入了title参数,对象的title属性就会被设置。如果没有传入,会被设置成默认值””。 我们可以创建一个方法来访问这个属性: zelda.loveTitle = function() { console.log( "I love " + this.title ); }; zelda.loveTitle(); // "I love Ocarina of Time" Game.prototype.heartIt = function() { console.log( "I heart " + this.title ); }; zelda.heartIt(); // "I heart Ocarina of Time" smb.heartIt(); // "I heart Super Mario Brothers" 结语 我希望这个教程对你学习JavaScript面向对象有用。JavaScript面向对象还有很多方面,以后的教程会再作介绍。如果有什么问题,请在下面留下评论。感谢您的阅读! 标签: <无> |