Inheritance of JS class

Keywords: Attribute

Catalog

Class JS

Writing class

inherit

get/set

Static

Method static modification

Attribute static decoration (special)

Class JS

Writing class

{
			class Parent{
				constructor(name="jini"){
					this.name=name;
				}
			}

			var v_parent=new Parent();
			console.log(v_parent);
		}

inherit

Take the Parent class above as the Parent class, and write a Studnet to inherit it

{
			class Parent{
				constructor(name="jini"){
					this.name=name;
				}
			}

			class Student extends Parent{
				constructor(name,age){
					super(name);
					this.age=age;
				}
			}
			var st = new Student("jjj",22);

			console.log(st);
			//{name: "jjj", age: 22}
		}

After using extends, all the properties of the parent class will be inherited

get/set

{
			class Parent{
				constructor(name="jini"){
					this.name=name;
				}
				get aname(){
					return this.name;
				}
				set aname(value){
					this.name=value;
				}
			}

			var pp = new Parent();
			pp.aname="jinjinjinjkin";
			console.log(pp.aname);
			//jinjinjinjkin
			//The set method is called for the parameter, and the get method is not called for the parameter
			//set and get must have the same name but not the same as the parameter name
		}


/ / set method is called for parameter, but get method is not called for parameter
/ / set and get must have the same name but not the same parameter name

Static

Method static modification

Methods modified by static can be called directly with class names without instantiating class objects

{
			class Parent{
				constructor(name,age){
					this.name=name;
					this.age=age;
				}
				static tell(){
					console.log(123);
				}
			}
			//Methods modified by static can be called directly with class names without instantiating class objects
			Parent.tell();
			//123
		}

Attribute static decoration (special)

{
			class Parent{
				constructor(name,age){
					this.name=name;
					this.age=age;
				}
			}
			Parent.sex="male";

			console.log(Parent.sex);
			let pp = new Parent("JIN",22);
			console.log(pp.sex);//undefined
			//Static properties cannot be called by instance objects, that is, by using new 
//The object call after operator instantiation, such as obj call in the above example, can only be called by class name, that is, obj call
		}

Parent.sex =; this is to define a static property for this class. This property cannot be called by the instantiated object, but only by the class name. In addition, all operations modify the same property parameter, which is loaded at the beginning

 

Posted by neveriwas on Sun, 05 Jan 2020 14:33:49 -0800