JavaScript static

把类比作函数,类里面的方法是添加到类的 prototype 对象上的,而如果声明了 static 方法,这个方法是直接添加到这个类的函数对象上的,而不是在这个函数的原型上的。例:

class Father{
	static fatherName(){console.log('father')}
	fatherSay(){console.log('i am father!')}
}

class Son extends Father{
	static sonName(){
		super.fatherName();
		console.log('son');
	}
	sonSay(){
		super.fatherSay()
		console.log('i am son!')
	}
}

Father.fatherName(); 	// 'father'

Son.fatherName();		// 'father'
Son.sonName();			// 'father'
						// 'son'

var son =new Son();
son.sonSay();			// 'i am father!'	
						// 'i am son!'
son.sonName;			// undefined
son.fatherName;			// undefined

从上面的例子可以看到,实例 son 里面没有 static 声明的方法,也就是说它们没有被放到 prototype 上。

  1. 既然它们没有被放到 prototype 里面,那么 Son.fatherName() 可以找到又说明,使用了 extends 继承的类,不仅关联了两个函数的 prototype,函数也进行了关联,也就是说 Son() 也关联了 Father()。
  2. 所以 static 也就放在这两个函数构造器之间的双向关系链上。
发布了45 篇原创文章 · 获赞 3 · 访问量 609

猜你喜欢

转载自blog.csdn.net/qq_40653782/article/details/103994491