JS类的static |
您所在的位置:网站首页 › 权限管理测试用例 › JS类的static |
static
类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。 语法 static methodName() { ... } 描述静态方法调用直接在类上进行,不能在类的实例上调用。静态方法通常用于创建实用程序函数。 调用静态方法 从另一个静态方法静态方法调用同一个类中的其他静态方法,可使用this关键字。 class StaticMethodCall { static staticMethod() { return 'Static method has been called'; } static anotherStaticMethod() { return this.staticMethod() + ' from another static method'; } } StaticMethodCall.staticMethod(); // 'Static method has been called' StaticMethodCall.anotherStaticMethod(); // 'Static method has been called from another static method' 从类的构造函数和其他方法非静态方法中,不能直接使用 this关键字来访问静态方法。而是要用类名来调用:CLASSNAME.STATIC_METHOD_NAME() ,或者用构造函数的属性来调用该方法: this.constructor.STATIC_METHOD_NAME(). class StaticMethodCall { constructor() { console.log(StaticMethodCall.staticMethod()); // 'static method has been called.' console.log(this.constructor.staticMethod()); // 'static method has been called.' } static staticMethod() { return 'static method has been called.'; } } public对象的成员都是public成员。任何对象都可以访问,修改,删除这些成员或添加新成员。主要有两种方式来在一个新对象里放置成员: 在构造函数里这种技术通常用来初始化public实例变量。构造函数的“this”变量用来给对象添加成员。 functin Container(param) { this.member = param; }这样,如果我们构造一个新对象var myContainer = new Container(‘abc’),则myContainer.member为’abc’。 在prototype里 这种技术通常用来添加public方法。当寻找一个成员并且它不在对象本身里时,则从对象的构造函数的prototype成员里找。 prototype机制用来做继承。为了添加一个方法到构造函数创建的所有对象里,只需添加到构造函数的prototype: Container.prototype.stamp = function (string) { return this.member + string; }这样,我们可以调用该方法myContainer.stamp(‘def’),结果为’abcdef’。 privateprivate成员由构造函数产生。普通的var变量和构造函数的参数都称为private成员。 function Container(param) { this.member = param; var secret = 3; var that = this; }该构造函数创建了3个private实例变量: param,secret和that。它们被添加到对象中,但是不能被外部访问,也不能被该对象自己的 public方法访问。它们只能由private方法访问。private方法是构造函数的内部方法。 function People () { this.name = "Yorhom"; var age = 16; this.getName = function () { return this.name }; this.getAge = function () { return age; }; } var yorhom = new People();// undefined alert(yorhom.age);// 16 alert(yorhom.getAge())例:编写js的类,使其拥有public和private类型的属性和方法 function People () { this.name = "Yorhom"; var age = 16; this.getName = function () { return this.name }; this.getAge = function () { return age; }; } var yorhom = new People();// undefined alert(yorhom.age);// 16 alert(yorhom.getAge()) protectedprotected可以修饰数据成员,构造方法,方法成员,不能修饰类(此处指外 部类,不考虑内部类)。被protected修饰的成员,能在定义它们的类中,同包 的类中被调用。如果有不同包的类想调用它们,那么这个类必须是定义它们的类 的子类。 //module foo: class Foo { constructor() { this[Foo.PROPERTY] = 'hello'; } test() { console.log(this[Foo.PROPERTY]); } } Foo.PROPERTY = Symbol(); export default Foo;//module bar: import Foo from '(module foo)'; class Bar extends Foo { test2() { console.log(this[Bar.PROPERTY]); } } export default Bar;//module main: import Bar from '(module bar)'; new Bar.test2(); |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |