创建自定义对象
// 创建一个Object的新实例,然后在实例上面添加属性和方法
const person = new Object();
person.name = "tiga";
person.age = 18;
person.running = function () {
console.log("柒");
};
工厂函数
function createObject(name, age, info) {
const obj = new Object();
obj.name = name;
obj.age = age;
obj.running = function () {
console.log(info);
};
return obj;
}
const person = createObject("tiga", 18, "啊柒");
const student = createObject("zeta", 16, "Carmel");
person.running(); // 啊柒
student.running(); // Carmel
构造函数模式
function Person(name, age, info) { this.name = name; this.age = age; this.running = function () { console.log(info); }; } const person = new Person("啊柒", 18, "啊柒");
const student = new Person("zeta", 16, "Carmel");
person.running(); // 啊柒
student.running(); // Carmel
原型模式
this.name = name;
this.age = age;
}
// 在这里,把方法running定义在了Person的prototype属性上 // person和student共享同一个原型方法running,指向的是同一快内存空间 Person.prototype.running = function (info) {
console.log(info);
};
const person = new Person("moment", 18);
const student = new Person("supper", 16); // 在构造函数中这里输出的是false
console.log(person.running === student.running); //true person.running("柒"); // 柒
student.running("Carmel"); //Carmel