总结: 直接定义在构造函数上的方法和属性是静态的, 定义在构造函数的原型和实例上的方法和属性是非静态的
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