目录
总的来说:静态的是指向类自身,而不是指向实例对象,主要是归属不同,这是静态属性,静态方法的核心。
分为:实例属性、静态属性(类属性)、只读属性
分为:实例方法、静态方法(类方法)
- class Person {
- //1、定义方法
- /* 1.1、实例属性,直接定义的属性,要new实例后,实例去访问的*/
- name= "tom";
- age = 10;
- /* 1.2、静态属性(类属性),通过static开头的属性,Person类可以访问,
- 不需要创建实例,实例访问不到 */
- static height = 180;
- /* 1.3、只读属性,readonly开头的属性,只可读,不可改*/
- readonly money= 1000;
-
- //2、定义方法
-
- say(){
- console.log('hello world');
- }
- static work(){
- console.log('我能挣钱');
- }
- }
- const per = new Person();
- //per.money=2000 报错,不可修改
- console.log(per, Person.height);
- per.say() //调用实例方法
- Person.work() //调用类方法
阻止方法被实例继承,类的内部相当于实例的原型,所有在类中直接定义的方法相当于在原型上定义方法,都会被类的实例继承,但是使用static静态方法定义的不会被实例继承。
- class User{
- static call(){
- console.log('你好呀');
- }
- }
- User.call()//你好呀
-
- let ff = new User()
- ff.call()//报错,实例不能访问类的静态方法
这里类User可以直接使用call方法,但它的是实例ff却不可以!
但是我们可以通过继承的方式,让另一个类来继承User里面的方法
- class User{
- static call(){
- console.log('你好呀');
- }
- }
-
-
- class foo extends User{}
- foo.call()//'你好呀'
这里foo类通过继承User类,才可以使用User里面的静态方法。
我们知道class类这个概念是es6后出来的新特性,用以前的es5方法写就是:
-
- class User{
- static call(){
- console.log('静态方法的你好呀');
- }
- call(){
- console.log('构造函数方法的你好呀');
- }
- }
-
- //等同于
- function User(){}
- User.call=function(){
- console.log('静态方法的你好呀');
- }
-
- User.prototype.call=function(){
- console.log('构造函数方法的你好呀');
- }
但是User类里面的构造函数方法是可以被实例调用的,如图:
- function User(){}
- User.prototype.call=function(){
- console.log('你好呀');
- }
- let h1 =new User()
- h1.call()//你好呀
完整版如下
- class User {
- call() {
- // 这里面的this指向构造函数的对象
- console.log(this === hh); // true
- console.log("构造函数方法的你好呀");
- }
- static call() {
- // 这里面的this指向类本身
- console.log(this === User); // true
- console.log("静态方法的你好呀");
- }
- }
- // 静态方法
- User.call(); //静态方法的你好呀
-
- // 构造函数方法
- let hh = new User();
- hh.call(); //构造函数方法的你好呀