function Star(name, age) {
this.name = name;
this.age = age;
this.sing = function () {
console.log(`${name}在唱歌`);
};
}
let 周杰伦 = new Star("周杰伦", 22);
let 蔡徐坤 = new Star("蔡徐坤", 20);
let 张韶涵 = new Star("张韶涵", 18);
let 张惠妹 = new Star("张惠妹", 28);
周杰伦.sing(); // "周杰伦在唱歌"
蔡徐坤.sing(); // "蔡徐坤在唱歌"
张韶涵.sing(); // "张韶涵在唱歌"
张惠妹.sing(); // "张惠妹在唱歌"
上例存在一个问题:每一个实例都存在 sing 方法,这会占据大量的内存空间,造成内存浪 费。 我们希望所有的对象使用同一个函数,这样就比较节省内存,那么我们要怎样做呢?
function Star(name, age) {
this.name = name;
this.age = age;
}
Star.prototype.sing = function () {
console.log(`${name}在唱歌`);
};
JavaScript 规定,每一个构造函数都有一个 prototype 属性,指向另一个对象(原型对象 )以上例子中,构造函数通过原型 prototype 分配的函数是所有对象所共享的。我们可以 把那些通用的方法,直接定义在 prototype 对象上,这样所有对象的实例就可以共享这些 方法。
function Star(name, age) {
this.name = name;
this.age = age;
}
Star.prototype = {
// 如果修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动利用 constructor 指回原来的构造函数
constructor: Star,
sing: function () {},
move: function () {},
eat: function () {},
sleep: function () {},
};
class Xing {
constructor(name, age) {
this.name = name;
this.age = age;
this.innerThis = function () {
return this;
};
}
outerThis() {
return this;
}
}
const zxc = new Xing("周星驰", 18);
console.log(zxc.innerThis() === zxc.outerThis()); // true
// 使用构造函数
function Star(name, age) {
this.name = name;
this.age = age;
}
Star.prototype = {
constructor: Star,
sing: function () {
console.log(this.name + "会唱歌");
},
move: function () {
console.log(this.name + "会移动");
},
};
// 使用class类
class Star {
constructor(name, age) {
this.name = name;
this.age = age;
}
sing() {
console.log(this.name + "会唱歌");
}
move() {
console.log(this.name + "会移动");
}
}