JS中ES6类和对象

tech2024-12-23  10

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> /*function Person(myName, myAge) { //实例属性 this.name=myName; this.age=myAge; //实例方法 this.say=function() { console.log(this.name, this.age); } //记住,静态方法是通过构造函数名作为对象的哈. Person.num=666; Person.run=function() { console.log("run"); } } let p=new Person("cyg",20); p.say(); console.log(Person.num); Person.run(); */ //以下es6 /*class Person { constructor(myName, myAge) { this.name = myName; this.age = myAge; } //es6中实例的和静态的属性与方法. //name="cyg"; //age=20; say() { console.log(this.name, this.age); } //以下静态 static num=666; static run() { console.log("run"); } } let p = new Person("zs", 18); p.say(); console.log(Person.num); Person.run();*/ /* class Person { // 在ES6标准中添加实例属性都需要在constructor中添加 constructor() { this.name="cyg"; this.age=20; } say() { console.log(this.name, this.age); } } let p = new Person(); console.log(p); */ /*class Person { // 在ES标准中static只支持定义静态方法不支持定义静态变量 // 大部分浏览器不支持静态变量的做法.会报错 // static num=666; static run() { console.log("run"); } } let p = new Person(); //console.log(Person.num); console.log(Person.run());*/ /*function Person(myName, myAge) { // 实例属性 this.name = myName; this.age = myAge; // 实例方法 this.hi = function () { console.log("hi"); } } Person.prototype.say=function() { console.log(this.name, this.age); } let p = new Person("lnj", 34); console.log(p.say());*/ //类没有去原型里面找 </script> </body> </html> <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> </style> </head> <body> <script type="text/javascript"> /*function Person(myName, myAge) { this.name=myName; this.age=myAge; this.hi=function() { console.log("h1"); } } /*Person.prototype.type="cyg"; Person.prototype.say=function() { console.log(this.name, this.age); }; */ //也可以这样写. /*Person.prototype={ constructor:Person, type:"cyg", say:function() { console.log(this.name, this.age); } };*/ class Person { constructor(myName, myAge) { this.name = myName; this.age = myAge; this.hi = function () { console.log("hi"); } } run() { console.log("run"); } } // Person.prototype.type = "人"; // Person.prototype.say = function () { // console.log(this.name, this.age); // }; let obj={constructor:Person,type:"cyg",say:function() { console.log(this.name, this.age); }}; Person.prototype=obj; let p = new Person("lnj", 34); console.log(p); </script> </body> </html>
最新回复(0)