1、利用JavaScript对象原型引用prototype来实现
var BaseClass = function() {};
BaseClass.prototype.method1 = function(){
alert(' This is a instance method ');
}
var instance1 = new BaseClass();
instance1.method1(); //This is a instance method
2、在实例上直接定义方法(对象)
var BaseClass = function() {};
var instance1 = new BaseClass();
instance1.method1 = function(){
alert(' This is a instance method too ');
}
instance1.method1();//This is a instance method too
3、通过this指针来定义实例方法 (变量)
var BaseClass = function() {
this.method1 = function(){
alert(' Defined by the "this" instance method');
}
};
var instance1 = new BaseClass();
instance1.method1();//Defined by the "this" instance method
那么同时咋实例、原型引用上和"this"上定义相同的实例方法后,实例会优先调用哪一个呢?
var BaseClass = function() {
this.method1 = function(){
alert(' Defined by the "this" in the instance method');
}
};
var instance1 = new BaseClass();
instance1.method1 = function(){
alert(' Defined directly in the instance method');
}
BaseClass.prototype.method1 = function(){
alert(' Defined by the prototype instance method ');
}
instance1.method1();//Defined directly in the instance method
* 通过运行结果跟踪测试可以看出直接砸实例上的变量的优先级要高于定义在“this”上的;
* 而定义在“this”上的又高于prototype定义的变量;
* 即直接定义在实例上的变量会覆盖定义在“this”上和prototype定义的变量,定义在“this'”上的会覆盖prototypetype定义的变量。