js中创建对象的方式
文章类型:Javascript
发布者:hp
发布时间:2023-03-07
我们在实际开发过程中,会遇到创建对象,总结一下创建对象的方式
一:{}
var o = {};
o.name = 'jack';
o.age = 20;
二: 通过对象字面量
person={firstname:"Mark",lastname:"Yun",age:25,eyecolor:"black"};
三: 通过构造函数
1:无参方式,通过new构造函数然后绑定属性
function Person(){}
var person=new Person();//定义一个function,如果使用new"实例化",该function可以看作是一个Class
person.name="Mark";
person.age="25";
person.work=function(){
alert(person.name+" hello...");
}
person.work();
2:有参方式,通过new构造函数传参方式,利用this作用域绑定到当前对象
function Pet(name,age,hobby){
this.name=name;//this作用域:当前对象
this.age=age;
this.hobby=hobby;
this.eat=function(){
alert("我叫"+this.name+",我喜欢"+this.hobby+",是个程序员");
}
}
var maidou =new Pet("麦兜",25,"coding");//实例化、创建对象
maidou.eat();//调用eat方法
四: 通过ES6 class关键字
class Polygon {
constructor(height, width) {
this.h = height;
this.w = width;
}
test() {
console.log("The height of the polygon: ", this.h)
console.log("The width of the polygon: ",this. w)
}
}
五:new Object
var o = new Object();
o.name = "zhangsna";
o.sayName = function(){
alert(this.name);
}
六:工厂模式
var wcDog =new Object();
wcDog.name="旺财";
wcDog.age=3;
wcDog.work=function(){
alert("我是"+wcDog.name+",汪汪汪......");
}
wcDog.work();
七:原型模式,挂在在对象原型上的属性和方法
function Dog(){}
Dog.prototype.name="旺财";
Dog.prototype.eat=function(){
alert(this.name+"是个吃货");
}
var wangcai =new Dog();
wangcai.eat();
八:构造函数+原型模式,通过构造函数传参,然后原型绑定方法
function Car(name,price){
this.name=name;
this.price=price;
}
Car.prototype.sell=function(){
alert("我是"+this.name+",我现在卖"+this.price+"万元");
}
var camry =new Car("凯美瑞",27);
camry.sell();
九:Object.create()
let newObj = Object.create(
{name:'sun'},
{
age: {
value: 24, // 属性默认值
congigurable: false, // 设置false之后将不能不删除
enumerable: true,
writable: false, // 设置false之后将不能修改
}
}
)