es6
class 内部都挂在 prototype 上,方便继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| class Father {
constructor(x, y) { console.log("new.target", new.target); if (new.target === Father) { this.x = x; this.y = y; } else if (typeof new.target !== "function") { throw new Error("必须使用 new 命令生成实例"); } }
get prop() { return "getter"; } set prop(value) { console.log("setter: " + value); }
static staticProp = 1; static classMethod() { this.staticProp = this.staticProp + "staticProp"; return "hello"; }
}
let f = new Father("X", "Y"); console.log(f);
console.log(Father === Father.prototype.constructor); console.log("f.prop ===", f.prop);
class Son extends Father { constructor(x, y) { super(x, y); console.log("new.target", new.target); } superToString() { return super.toString(); } static classMethod() { return super.classMethod() + ", 从super对象上调用父类静态方法"; } }
|
es5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function Person() { insideProperty = "insideProperty"; this.name = "张三"; this.age = 20; this.run = function () { console.log(this.name + "在运动"); }; }
Person.prototype.sex = "男";
Person.prototype.work = function () { console.log(this.name + "在工作"); };
Person.getInfo = function () { console.log("静态方法,类独享"); };
let p = new Person(); let p2 = new Person(); console.log(Person.getInfo()); console.log("p.name", p.name); p2.name = "p2-name"; console.log("p.name 是否被 p2 影响", p.name === p2.name, p.name); p.run(); p.work(); Person.insideProperty; p.insideProperty;
|