读书人

JavaScript:运用面向对象的技术创建高

发布时间: 2012-10-29 10:03:53 作者: rapoo

JavaScript:使用面向对象的技术创建高级 Web 应用程序

目录 JavaScript 对象是词典
JavaScript 函数是最棒的
构造函数而不是类
原型
静态属性和方法
闭包
模拟私有属性
从类继承
模拟命名空间
应当这样编写 JavaScript 代码吗?
展望
var userObject = new Object();userObject.lastLoginTime = new Date();alert(userObject.lastLoginTime); var userObject = {}; // equivalent to new Object()userObject[“lastLoginTime”] = new Date();alert(userObject[“lastLoginTime”]);var userObject = { “lastLoginTime”: new Date() };alert(userObject.lastLoginTime);?function func(x) { alert(x);}func(“blah”);var func = function(x) { alert(x);};func(“blah2”);var func = new Function(“x”, “alert(x);”);func(“blah3”);?function sayHi(x) { alert(“Hi, “ + x + “!”);}sayHi.text = “Hello World!”;sayHi[“text2”] = “Hello World... again.”;alert(sayHi[“text”]); // displays “Hello World!”alert(sayHi.text2); // displays “Hello World... again.”// assign an anonymous function to a variablevar greet = function(x) { alert(“Hello, “ + x);};greet(“MSDN readers”);// passing a function as an argument to anotherfunction square(x) { return x * x;}function operateOn(num, func) { return func(num);}// displays 256alert(operateOn(16, square));// functions as return valuesfunction makeIncrementer() { return function(x) { return x + 1; };}var inc = makeIncrementer();// displays 8alert(inc(7));// functions stored as array elementsvar arr = [];arr[0] = function(x) { return x * x; };arr[1] = arr[0](2);arr[2] = arr[0](arr[1]);arr[3] = arr[0](arr[2]);// displays 256alert(arr[3]);// functions as object propertiesvar obj = { “toString” : function() { return “This is an object.”; } };// calls obj.toString()alert(obj);var myDog = { “name” : “Spot”, “bark” : function() { alert(“Woof!”); }, “displayFullName” : function() { alert(this.name + “ The Alpha Dog”); }, “chaseMrPostman” : function() { // implementation beyond the scope of this article } };myDog.displayFullName(); myDog.bark(); // Woof!function displayQuote() { // the value of “this” will change; depends on // which object it is called through alert(this.memorableQuote); }var williamShakespeare = { “memorableQuote”: “It is a wise father that knows his own child.”, “sayIt” : displayQuote};var markTwain = { “memorableQuote”: “Golf is a good walk spoiled.”, “sayIt” : displayQuote};var oscarWilde = { “memorableQuote”: “True friends stab you in the front.” // we can call the function displayQuote // as a method of oscarWilde without assigning it // as oscarWilde’s method. //”sayIt” : displayQuote};williamShakespeare.sayIt(); // true, truemarkTwain.sayIt(); // he didn’t know where to play golf// watch this, each function has a method call()// that allows the function to be called as a // method of the object passed to call() as an// argument. // this line below is equivalent to assigning// displayQuote to sayIt, and calling oscarWilde.sayIt().displayQuote.call(oscarWilde); // ouch!?alert(“NaN is NaN: “ + isNaN(NaN));function x() { this.isNaN = function() { return “not anymore!”; };}// alert!!! trampling the Global object!!!x();alert(“NaN is NaN: “ + isNaN(NaN));?Dog spot = new Dog();function DogConstructor(name) { this.name = name; this.respondTo = function(name) { if(this.name == name) { alert(“Woof”); } };}var spot = new DogConstructor(“Spot”);spot.respondTo(“Rover”); // nopespot.respondTo(“Spot”); // yeah!var spot = new DogConstructor(“Spot”);// create an empty objectvar spot = {}; // call the function as a method of the empty objectDogConstructor.call(spot, “Spot”);// Think of this as class Dogfunction Dog(name) { // instance variable this.name = name; // instance method? Hmmm... this.respondTo = function(name) { if(this.name == name) { alert(“Woof”); } };}var spot = new Dog(“Spot”);?function respondTo() { // respondTo definition}function Dog(name) { this.name = name; // attached this function as a method of the object this.respondTo = respondTo;}?var buddy = new Dog(“Buddy“);?buddy 所引用的对象将从它的原型继承属性和方法,尽管仅从这一行可能无法明确判断原型来自哪里。对象 buddy 的原型来自构造函数(在这里是函数 Dog)的属性。var spot = new Dog(“Spot”);// Dog.prototype is the prototype of spotalert(Dog.prototype.isPrototypeOf(spot));// spot inherits the constructor property// from Dog.prototypealert(spot.constructor == Dog.prototype.constructor);alert(spot.constructor == Dog);// But constructor property doesn’t belong// to spot. The line below displays “false”alert(spot.hasOwnProperty(“constructor”));// The constructor property belongs to Dog.prototype// The line below displays “true”alert(Dog.prototype.hasOwnProperty(“constructor”));?JavaScript:运用面向对象的技术创建高级 Web 应用程序Dog.prototype = new Object();?function GreatDane() { }var rover = new GreatDane();var spot = new GreatDane();GreatDane.prototype.getBreed = function() { return “Great Dane”;};// Works, even though at this point// rover and spot are already created.alert(rover.getBreed());// this hides getBreed() in GreatDane.prototypespot.getBreed = function() { return “Little Great Dane”;};alert(spot.getBreed()); // but of course, the change to getBreed // doesn’t propagate back to GreatDane.prototype// and other objects inheriting from it,// it only happens in the spot objectalert(rover.getBreed());?function DateTime() { } // set static method now() DateTime.now = function() { return new Date(); }; alert(DateTime.now());?function filter(pred, arr) { var len = arr.length; var filtered = []; // shorter version of new Array(); // iterate through every element in the array... for(var i = 0; i < len; i++) { var val = arr[i]; // if the element satisfies the predicate let it through if(pred(val)) { filtered.push(val); } } return filtered;}var someRandomNumbers = [12, 32, 1, 3, 2, 2, 234, 236, 632,7, 8];var numbersGreaterThan100 = filter( function(x) { return (x > 100) ? true : false; }, someRandomNumbers);// displays 234, 236, 632alert(numbersGreaterThan100);var greaterThan300 = filter( function(x) { return (x > 300) ? true : false; }, someRandomNumbers);function makeGreaterThanPredicate(lowerBound) { return function(numberToCheck) { return (numberToCheck > lowerBound) ? true : false; };}var greaterThan10 = makeGreaterThanPredicate(10);var greaterThan100 = makeGreaterThanPredicate(100);alert(filter(greaterThan10, someRandomNumbers));alert(filter(greaterThan100, someRandomNumbers));?function Person(name, age) { this.getName = function() { return name; }; this.setName = function(newName) { name = newName; }; this.getAge = function() { return age; }; this.setAge = function(newAge) { age = newAge; };}var ray = new Person(“Ray”, 31);alert(ray.getName());alert(ray.getAge());ray.setName(“Younger Ray”);// Instant rejuvenation!ray.setAge(22);alert(ray.getName() + “ is now “ + ray.getAge() + “ years old.”);function Person(name, age) { var occupation; this.getOccupation = function() { return occupation; }; this.setOccupation = function(newOcc) { occupation = newOcc; }; // accessors for name and age }Person.prototype.somePublicMethod = function() { // doesn’t work! // alert(this.name); // this one below works alert(this.getName());};?// class Petfunction Pet(name) { this.getName = function() { return name; }; this.setName = function(newName) { name = newName; };}Pet.prototype.toString = function() { return “This pet’s name is: “ + this.getName();};// end of class Petvar parrotty = new Pet(“Parrotty the Parrot”);alert(parrotty);// class Dog : Pet // public Dog(string name, string breed)function Dog(name, breed) { // think Dog : base(name) Pet.call(this, name); this.getBreed = function() { return breed; }; // Breed doesn’t change, obviously! It’s read only. // this.setBreed = function(newBreed) { name = newName; };}// this makes Dog.prototype inherits// from Pet.prototypeDog.prototype = new Pet();// remember that Pet.prototype.constructor// points to Pet. We want our Dog instances’// constructor to point to Dog.Dog.prototype.constructor = Dog;// Now we override Pet.prototype.toStringDog.prototype.toString = function() { return “This dog’s name is: “ + this.getName() + “, and its breed is: “ + this.getBreed();};// end of class Dogvar dog = new Dog(“Buddy”, “Great Dane”);// test the new toString()alert(dog);// Testing instanceof (similar to the is operator)// (dog is Dog)? yesalert(dog instanceof Dog);// (dog is Pet)? yesalert(dog instanceof Pet);// (dog is Object)? yesalert(dog instanceof Object);?var MSDNMagNS = {};MSDNMagNS.Pet = function(name) { // code here };MSDNMagNS.Pet.prototype.toString = function() { // code };var pet = new MSDNMagNS.Pet(“Yammer”);var MSDNMagNS = {};// nested namespace “Examples”MSDNMagNS.Examples = {}; MSDNMagNS.Examples.Pet = function(name) { // code };MSDNMagNS.Examples.Pet.prototype.toString = function() { // code };var pet = new MSDNMagNS.Examples.Pet(“Yammer”);// MSDNMagNS.Examples and Pet definition...// think “using Eg = MSDNMagNS.Examples;” var Eg = MSDNMagNS.Examples;var pet = new Eg.Pet(“Yammer”);alert(pet); function object(o) { function F() {} F.prototype = o; return new F(); }?然后,由于 JavaScript 中的对象是可延展的,因此可以方便地在创建对象之后,根据需要用新字段和新方法增大对象。MyNamespace.MyClass = function() { MyNamespace.MyClass.initializeBase(this); this._myProperty = null;}Then, you need to define the class members itself in its prototype:MyNamespace.MyClass.prototype = { get_myProperty: function() { return this._myProperty;}, set_myProperty: function(value) { this._myProperty = value; }, doSomething: function() { MyNamespace.MyClass.callBaseMethod(this, “doSomething”); /* do something more */ }}MyNamespace.MyClass.registerClass( “MyNamespace.MyClass “, MyNamespace.BaseClass);?此处不需要管理构造函数和原型层次结构,因为这由 registerClass 函数自动完成的。

[转自:http://msdn.microsoft.com/zh-cn/magazine/cc163419.aspx]

读书人网 >Web前端

热点推荐