javascript可以定义实例方法吗
时间:2022-02-11 17:19
javascript可以定义实例方法,方法:1、利用JavaScript对象原型引用prototype来实现实例方法;2、在对象实例上直接定义方法;3、通过this指针来定义实例方法。 本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 1、利用JavaScript对象原型引用prototype来实现实例方法 2、在实例上直接定义方法(对象) 3、通过this指针来定义实例方法 (变量) 那么同时咋实例、原型引用上和"this"上定义相同的实例方法后,实例会优先调用哪一个呢? * 通过运行结果跟踪测试可以看出直接砸实例上的变量的优先级要高于定义在“this”上的; * 而定义在“this”上的又高于prototype定义的变量; * 即直接定义在实例上的变量会覆盖定义在“this”上和prototype定义的变量,定义在“this'”上的会覆盖prototypetype定义的变量。 【推荐学习:javascript高级教程】 以上就是javascript可以定义实例方法吗的详细内容,更多请关注gxlsystem.com其它相关文章!var BaseClass = function() {};
BaseClass.prototype.method1 = function(){
alert(' This is a instance method ');
}
var instance1 = new BaseClass();
instance1.method1(); //This is a instance method
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
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
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