JS 面向对象编程

this

function speak(line){
    print("The " + this.abjective + "rabbit says '" + line + "'");
}
var whiteRabbit = {abjective:"white",speak:speak};
whiteRabbit.speak("I'am late");
speak.apply(whiteRabbit,["I'am late"]); //传入参数数组
speak.call(whiteRabbit,"I'am late");    //参数单独传入

whiteRabbit即是this

构造函数

new调用函数,函数的this会返回(除非用return返回特定值)

function Rabbit(abjective){
    this.abjective = abjective;
    this.speak = function(line){
        print("The " + this.abjective + "rabbit says '" + line + "'");
    }
}
var killerRabbit = new Rabbit("killer");
killerRabbit.speak("GRAAAAAAAH!");

从原型中构建

function makeRabbit(abjective){
    return {
        abjective:abjective;
        speak://....
    }
}
blackRabbit = makeRabbit("black");

两者的区别是:killerRabbitconstructor指向Rabbit
blackRabbitconstructor指向Object
constructortoString都是Object原型的一部分