<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//1.构造函数方式
function A() {
this.name = '时分秒';
this.age = 22;
this.info = ['55kg', '180cm'];
this.skill = function () {
console.log('我能吃');
}
}
//实例化对象,每实例化一次,会占用一个内存空间
var a = new A();
var a1 = new A();
var a2 = new A();
//缺点:这种方式定义的对象会占用很多内存,因为每个对象创建单独的空间,存储各自的内容
//2.原型对象方式
function B() {
B.prototype.name = '犬夜叉';
B.prototype.age = 25;
B.prototype.info = ['66kg', '185cm'];
B.prototype.skill = function () {
console.log('我能打');
}
}
//实例化对象,每次实例都将指向原型对象
var b = new B();
var b1 = new B();
var b2 = new B();
b.info.push('strong');
console.log(b1.info); //结果:(3) ["66kg", "185cm", "strong"]
//缺点:当改变一个对象的引用类型的属性后,其他对象也发生了变化
//3.混合方式定义
function C(){
this.name = '奈落';
this.age = '200';
this.info = ['190cm', '60kg']
}
C.prototype.skill = function () {
console.log('我会骗');
}
var c = new C();
C.prototype.skill();
//混合是指构造函数方式和原型对象方式混合,将属性放到构造函数内部,将成员方法放到原型对象中。
//4.动态混合方式
function D() {
this.name = '桔梗';
this.age = 22;
this.info = ['178cm', '50kg']
if(!D.prototype.skill){
D.prototype.skill = function () {
console.log('我爱阿狸');
}
}
}
var d = new D();
d.skill();
//有些类似PHP中的单例模式
</script>
</body>
</html>
代码-JS之定义对象的方式
猜你喜欢
转载自blog.csdn.net/qq_39723600/article/details/83239589
今日推荐
周排行