js创建对象的几种方式以及利用原型操作内置对象

109 阅读1分钟

1.JS创建对象的方式

字面量方式创建对象:代码结构简单,适用于单个对象的创建使用,缺点是大批量创建对象效率低下,代码会臃肿

let stu = {
	name:"张三疯",
	age :22,
	sex:"男"show:function(){
		console.log(stu.name+stu.age+this.sex);
	}
}
console.log(stu.name);
stu.show();

工厂函数创建对象的方式

function createStu(name,age,sex){
	let obj = {};
	obj.name = name;
	obj.age = age;
	obj.sex = sex;
	obj.show = function(){
		console.log(obj.name+obj.age+obj.sex);	
	}
	return obj;
}
let stu2 = createStu("lisi",18,"女");
stu2.show();
console.log(stu2.sex);

构造函数创建对象的方式

function Student(){
	this.name = name;
	this.age = age;
	this.sex = sex;
}
Student.prototype.show = function(){
	console.log(this.name+this.age+this.sex);
}
let stu4 = new Student("赵六"15,“女”);
console.log(stu4.sex);
console.log(Student.prototype === stu4.__proto__);
console.log(Student.prototype);
console.log(stu4.__proto__);

2.使用原型方式来解决数据共享问题

首先这边有一个函数

function Student(name,age,sex){
	this.name = name;
	this.age = age;
	this.sex = sex;
	this.show = function(){
		console.log(this.name+this.age+this.sex);
	}
}

通过原型的方式来解决数据共享问题

Student.prototype.play = function(){
	console.log("play games");
}
Student.prototype.color = "yellow";
let stu1 = new Student("张三"18"男");
let stu2 = new Student("李四",21,"女");
stu1.play();
stu2.play();
console.log(stu1.color);
console.log(stu2.color);
console.log(stu1.play = stu2.play);//stu1 和stu2调用的paly是同一个函数
//通过对象获取原型对象
console.log(stu1.__proto__);
//通过类来获取原型对象
console.log(Student.prototype);
//通过对象来获取构造函数
console.log(stu1.__proto__.constructor);
//通过类的原型来获取构造函数
console.log(Student.prototype.constructor);
//对象本身可以直接获取构造函数
console.log(stu1.constructor);

prototype属性属于构造函数(类),__proto__属于实例化出来的对象。 prototype是标准属性,__proto__是非标准属性 通过构造函数方式实例化出来的对象,内部包含一个指向构造函数的原型对象(proto) 所有实例对象,都会直接或间接的继承原型对象

3.使用原型操作内置对象

let d = new Date();
    let time = d.getFullYear() + "-" + (d.getDay() + 1) + '-' + d.getDate();
    console.log(time);
    Date.prototype.formatTime = function () {
        let time = this.getFullYear() + "-" + (this.getDay() + 1) + '-' + this.getDate();
        return time;
    }
    let d2 = new Date();
    console.log(d2.formatTime());
    String.prototype.sayHi = function () {
        console.log(this + '你好帅');
    }
    let str = '吴彦祖';
    str.sayHi();
    Array.prototype.numberSort = function () {
        console.log(this);
        for (let i = 0; i < this.length; i++) {
            for (let j = 0; j < this.length; j++) {
                if (this[j] > this[j + 1]) {
                    let temp = this[j];
                    this[j] = this[j + 1];
                    this[j + 1] = temp;
                }
            }
        }
    }
    let arr = [11, 10, 22, 34, 14, 25, 66, 87];
    arr.numberSort();
    console.log(arr);