javascript创建对象的三种方法

  • 2019-01-07 12:00:27
  • 2,444 次阅读
  • 稿源:天马行空

面向对象:我们什么都不用管,直接找到一个会做事的”对象”来帮助我们完成任务,jQuery就是一个面向对象的例子,他们把一些方法和属性都给我们封装好了,我们可以不去了解其内部是如何实现,只要拿到它会使用就可 以了。下面是使用原生的js创建对象,会帮助我们更好的理解面向对象。

(1)最终代码图:

obj

(2)代码过程:

<script type="text/javascript"> 
 // 第一种方法:通过Json的方式创建对象
person = {
    'name':'马行行',
    'age': 18,
    'gender': '男',
    'sayHello' : function() {
    alert('你好,我是' + this.name + ',芳年' + this.age + ',性别:' + this.gender);
    }
};
// person.sayHello();
   person['sayHello']();
// 第二种方法:通过new关键字创建对象
    mobile = new Object();
    mobile.brand = 'huawei';
    mobile.color = 'white';
    mobile.introduce = function() {
    console.log('我的手机品牌是' + this.brand + ',颜色是' + this.color);
    }
    mobile.introduce();
// 第三种方法:通过构造函数创建对象(构造函数就是模板)
// 第三种的第一种形式
Student = function() {
    this.name = '小明';
    this.studentID = 128126;
    this.study = function() {
    alert('我叫' + this.name + ',学号:' + this.studentID);
    }
};
    s = new Student();
    alert(s.name);
    s.study();
// 第三种的第二种形式
Car = function(newbrand,newColor) {
    this.brand = newbrand;
    this.color = newColor;
    this.run = function() {
    alert('路上跑着一辆' + this.color + this.brand);
    }
};
    c = new Car('兰博基尼','红色');
    c.run();
// 第三种的第三种形式
Computer = function(obj) {
    this.brand = obj.newBrand;
    this.color = obj.newColor;
    this.netPlay = function() {
    alert('这是一台' + this.color + this.brand + '笔记本电脑');
    }
};
    var target = {newBrand:'联想',newColor:'黑色'}
    var c = new Computer(target);
    c.netPlay();
// 第三种的第四种形式
// Desk.prototype是Desk的原型属性,只与自己的对象有关
// Desk.prototype是d的原型对象
// prototype是标准的,__proto__是非标准的,做调试用
// 如果对象中没有该属性或方法,就会到与之相关的prototype中去寻找
// 原型属性不会共享,只会添加;原型方法可以共享
Desk = function(obj) {
    this.length = obj.newLength;
    this.width = obj.newWidth;
}
Desk.prototype.height = '1.2米';
Desk.prototype.put = function() {
    alert('桌子用来摆放东西');
}
var d = new Desk({newLength:'1.5米',newWidth:'1米'});
// alert(d.length);
// alert(d.height);
    d.put();
// 第三种的第五种形式
Cup = function(obj) {
    this.shape = obj.newShape;
    this.color = obj.newColor;
}
Cup.prototype = {
    sh:function() {
    alert(this.shape);
},
    co:function() {
    alert(this.color);
}
}
var cu = new Cup({newShape:'圆形',newColor:'蓝色'});
    alert(cu.shape);
    cu.sh();
    cu.co();
// 第三种的第六种形式
Blog = function(obj) {
    this._init(obj)
}
Blog.prototype = {
    _init:function(obj) {
        this.domain = obj.domain;
        this.host = obj.host;
    },
        display:function() {
        alert(this.domain + this.host);
    }
}
var b = new Blog({domain:'maxing128.com',host:'阿里云'});
    b.display();
    alert(b.domain);
</script>
喜欢 2

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头