最新下载
热门教程
- 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代码运行工具:测试上述代码,可获得如下运行结果:
相关文章
- 高达破坏者4游戏关卡数量介绍说明 11-07
- 燕云十六声虎骨酒怎么刷-虎骨酒速刷攻略 11-07
- 高达破坏者4无法加入团队模式说明 11-07
- 高达破坏者4浮游炮可用机体介绍说明 11-07
- 高达破坏者4强袭自由获取方法攻略分享 11-07
- 高达破坏者4零件收集获取方法攻略分享 11-07


