首页 > csdn导入, 技术, 读书笔记/书评 > JavaScript高级程序设计读书笔记(二)

JavaScript高级程序设计读书笔记(二)

2006年11月10日 发表评论 阅读评论

终于有一本书的读书笔记写到第二篇了,呵呵~~不过这本书的第一篇读书笔记更像是速记的内容:)
1. Javascript只有public作用域,没有private,更不用说protected,另外也没有静态方法。
2. this指向的是调用该方法的对象
    obj.color = “red”;
    obj.show = function(){
       alert(this.color);    //output “red”
    }
3. 定义类的几种方法(略去最后一种,根本没看懂,而且说非常不推荐这种做法)
(1) Factory
function showColor(){
    alert(this.color);
}
function createCar(color, doors, mpg){
    var temp = new Object;
    temp.color = color;
    temp.doors = doors;
    temp.mpg = mpg;
    temp.showColor = showColor;
}

var car = createCar(“red”, 4, 23);
缺点:没有共享函数。不同的实例间可能有不同的函数调用。可以改变一个对象的函数绑定。不用new构造,不像是类(当然,只是不像)。
(2) Constructor
function Car(color, doors, mpg){
    this.color = color;
    this.doors = doors;
    this.mpg = mpg;
    this.showColor = function(){
       alert(this.color);
    }
}

var car = new Car(“red”, 4, 23);
优点:用new构造
缺点:同工厂的第一点。
(3)Prototype
function Car(){}
Car.prototype.color = “red”;
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.showColro = function(){
    alert(this.color);
}

var car = new Car();
优点:函数真正共享,不会出现不同实例之间使用不同函数的情况(指的是同一函数名的情况下,同时Javascript里不存在函数重载)。可以使用car instanceof Car
缺点:显而易见,函数共享的同时把属性也共享了,没什么比这个更糟糕的了。
(4) Mixed Constructor/Prototype
function Car(color, doors, mpg){
    this.color = color;
    this.doors = doors;
    this.mpg = mpg;
}
Car.prototype.showColor = function(){
    alert(this.color);
}

var car = new Car(“red”, 4, 23);
优点:函数真正共享,但不共享属性。不过我发现可以把属性加入prototype来实现静态的属性。也可以使用car instanceof Car
(5) Dymanic Prototype
function Car(color, doors, mpg){
    …
    if(typeof Car._initialized == “undefined”){
       Car.prototype.showColor = function(){
          alert(this.color);
        }
    Car._initialized = true;
    }
}
这个更大的进步就在于,函数的创建只有一次了。
4. 一个StringBuffer实例,通过Array.join()来实现append()。同时还有实现Array.indexOf()方法(这个Prototype.js里也有的)。前面一个用的是构造类,后面用的是prototype

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word


Warning: fsockopen() has been disabled for security reasons in /home/onlymars/public_html/wp/wp-includes/class-snoopy.php on line 1148