1 Star 0 Fork 0

math.most/js_study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
020对象创建模式.js 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
Administrator 提交于 2021-05-10 22:59 +08:00 . js up study
/**
* 对象创建方式一
*/
let person = new Object();
person.name = 'tom';
person.age = 18;
person.setName = function (newName) {
this.name = newName;
};
// 测试
person.setName('jack');
console.log(person.name); // jack
/**
* 对象创建方式二
*/
let color = {
name: 'yellow',
size: 3,
setName: function (newName) {
this.name = newName;
}
}
// 测试
color.setName('black');
console.log(color.name); // black
/**
* 工厂模式创建
*/
function createPerson (name, age) {
let person = {
name: name,
age: age,
setName: function (newName) {
this.name = newName;
}
};
return person;
}
// 测试
let p1 = createPerson('小红', 18);
let p2 = createPerson('小黄', 28);
p1.setName('小红人');
console.log(p1.name, p1.age); // 小红人 18
p2.setName('小黄人');
console.log(p2.name, p2.age); // 小黄人 28
/**
* 工厂模式 + 原型绑定创建
*/
function ProtoCar (name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
ProtoCar.prototype.sayName = function () {
console.log(this.name);
}
var car1 = new ProtoCar('奥迪', 6, '80万');
car1.sayName(); // 奥迪
var car2 = new ProtoCar('宝马', 8, '60万');
car2.sayName(); // 宝马
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/mathmost/js_study.git
git@gitee.com:mathmost/js_study.git
mathmost
js_study
js_study
master

搜索帮助