最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JavaScript基础之静态方法和实例方法分析
时间:2022-06-25 15:25:40 编辑:袖梨 来源:一聚教程网
本文实例讲述了JavaScript静态方法和实例方法。分享给大家供大家参考,具体如下:
直接定义在构造函数上的方法和属性是静态的, 定义在构造函数的原型和实例上的方法和属性是非静态的
/* -- 静态方法 -- */
function ClassA() { //定义构造函数
};
ClassA.func = function() { //在构造函数上添加一个属性(因为函数也是对象)
console.log("This is a static method");
}
var instance = new ClassA(); //新建一个实例
ClassA.func(); //This is a static method
instance.func(); //Error:instance.func is not a function
可获得如下运行结果:
/* --- 实例方法 -- */
function ClassA() { //定义构造函数
};
ClassA.prototype.func = function() { //在构造函数的原型上添加方法
console.log("This is an instance method.");
}
var instance = new ClassA(); //新建一个实例
ClassA.func(); // Error:ClassA.func is not a function
instance.func(); //This is an instance method.
使用在线HTML/CSS/JavaScript代码运行工具:测试上述代码,可获得如下运行结果:
// 定义在某个具体对象(实例)上的方法是实例方法
function ClassA() { //定义构造函数
};
var instance = new ClassA(); //新建一个实例
instance.func = function() {
console.log("This is an instance method.")
}
// ClassA.func(); // Error:ClassA.func is not a function
instance.func(); //This is an instance method.
使用在线HTML/CSS/JavaScript代码运行工具:测试上述代码,可获得如下运行结果:
相关文章
- Ubuntu通过wine安装QQ无法输入账号怎么办? 09-12
- Ubuntu系统中WPS不能输入中文该怎么办? 09-12
- 快速释放Ubuntu磁盘空间的七种方法 09-12
- Ubuntu系统中怎么设置IP地址? 09-12
- ubuntu挂载移动硬盘出现错误 mountunknown filesystem type exfat 09-12
- ubuntu怎么进入指定的文件夹并更改路径? 09-12


