javascript原生创建对象的多种方式

2020-4-10 16:21:38
学习记录
114

创建对象的多种方式

工厂模式

function Person(name){ var obj = new Object(); obj.name = name; obj.getName = function(){ console.log(this.name); } return obj; } var person1 = Person('li');

构造函数模式

function Person(name){ this.name = name; this.getName = getName; }; function getName = function(){ console.log(this.name); } var person1 = new Person('Li');

原型模式

function Person(name){}; Person.prototype = { constructor:Person, name:'Lio', getName:function(){ console.log(this.name); } }; var person1 = new Person();

组合模式(构造函数+原型)

function Person(name){ this.name = name; } Person.prototype = { constructor:Person, getName:function(){ console.log(this.name); } } var person1 = new Person('Li');

动态原型模式

寄生构造函数模式

function Person(name){ var obj = new Object(); obj.name = name; obj.getName = function(){ console.log(this.name); } return obj; } var person1 =new Person('li');

稳妥构造函数模式

function Person(name){ var o = new Object(); o.name = name; o.getName = function(){ console.log(o.name); } return o; } var person1 = person('kevin'); person1.sayName(); // kevin person1.name = "daisy"; person1.sayName(); // kevin console.log(person1.name); // daisy

js创建对象的多种方式

avatar

Sky(小新)

个人签名: 提升能力,创造价值!

江苏-南京
skylpz@qq.com