JavaScript 静态方法和实例方法

本文探讨JavaScript中的静态方法和实例方法。静态方法是定义在构造函数上,只能通过对象本身访问,不能被实例对象调用。实例方法则定义在构造函数的原型或实例上,可通过对象实例调用。数组的`Array.from`和`Array.of`是静态方法,而大部分其他数组方法如`push`、`pop`等是实例方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结: 直接定义在构造函数上的方法和属性是静态的, 定义在构造函数的原型和实例上的方法和属性是非静态的

1.静态方法:

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 Obj(){
                
}
            
Obj.a=0; //静态变量
            
Obj.fn=function(){ //静态函数
                    
 }
            
 console.log(Obj.a); //0
 console.log(typeof Obj.fn); //function
            
var o=new Obj();
console.log(o.a); //undefined
console.log(typeof o.fn); //undefined

静态方法不能被实例对象调用,实例方法不能被构造对象调用。

2.非静态方法/实例方法(定义在原型或实例上):

// 1.定义在构造函数原型上的方法是实例方法 
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.

// 2.定义在某个具体对象(实例)上的方法是实例方法
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.

3.数组中静态方法和实例方法

那么我们就拿数组的方法来举例。

静态方法: Array的新方法from/of都是。在控制台输入 Object.getOwnPropertyNames(Array)就可以看到他们的名字。

Object.getOwnPropertyNames(Array) 
["length", "name", "prototype", "isArray", "from", "of"]

实例方法:Array的大部分方法都是。在控制台输入Object.getOwnPropertyNames(Array.prototype)

["length", "constructor", "concat", "copyWithin", "fill", "find", "findIndex", "lastIndexOf", "pop", "push", "reverse", "shift", "unshift", "slice", "sort", "splice", "includes", "indexOf", "join", "keys", "entries", "forEach", "filter", "map", "every", "some", "reduce", "reduceRight", "toLocaleString", "toString", "values", "flat", "flatMap"]

参考文章:
https://www.cnblogs.com/roger9567/p/5048276.html
https://blog.youkuaiyun.com/wc11223/article/details/70561114
https://www.cnblogs.com/hanguidong/p/9296697.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值