javascript能定义实例方法吗

发布时间:2021-11-22 14:42:10 作者:iii
来源:亿速云 阅读:126

这篇文章主要介绍“javascript能定义实例方法吗”,在日常操作中,相信很多人在javascript能定义实例方法吗问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”javascript能定义实例方法吗”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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能定义实例方法吗”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. javascript能代替php吗
  2. php能代替javascript吗

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript

上一篇:Python的if语法怎么使用

下一篇:c语言怎么实现含递归清场版扫雷游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》