javascript可以定义实例方法吗

青灯夜游
发布: 2021-11-22 14:03:18
原创
1927人浏览过
javascript可以定义实例方法,方法:1、利用JavaScript对象原型引用prototype来实现实例方法;2、在对象实例上直接定义方法;3、通过this指针来定义实例方法。

javascript可以定义实例方法吗

本教程操作环境: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指针来定义实例方法  (变量)

立即学习Java免费学习笔记(深入)”;

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可以定义实例方法吗的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号