javascript可以定义实例方法,方法:1、利用JavaScript对象原型引用prototype来实现实例方法;2、在对象实例上直接定义方法;3、通过this指针来定义实例方法。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
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定义的变量。
【推荐学习:javascript高级教程】
以上就是javascript可以定义实例方法吗的详细内容,更多请关注美工之家9502669.com其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。