javascript - 面向对象

本文介绍了JavaScript中的对象概念,包括如何创建对象以及使用prototype属性来扩展对象的功能。通过具体示例展示了如何利用prototype来添加新的属性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下代码为变量 car 设置值为 "Fiat" :

var car = "Fiat";

对象也是一个变量,但对象可以包含多个值(多个变量)。

var car = {type:"Fiat", model:500, color:"white"};

在以上实例中,3 个值 ("Fiat", 500, "white") 赋予变量 car。

在以上实例中,3 个变量 (type, model, color) 赋予变量 car。

NoteJavaScript 对象是变量的容器

 prototype 属性


定义和用法

prototype 属性允许您向对象添加属性和方法

注意: Prototype 是全局属性,适用于所有的Javascript对象。

语法

object.prototype.name=value

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>
        function employee(name, jobtitle, born) {
            this.name = name;
            this.jobtitle = jobtitle;
            this.born = born;
        }
        var fred = new employee("Fred Flintstone", "Caveman", 1970);
 
        employee.prototype.salary = null;
 
        fred.salary = 20000;
 
        document.write(fred.salary);
    </script>

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function Person(name) {
    var _this = {};
    _this._name = name;
 
    _this.sayHello = function() {
        alert("P_hello" + _this._name);
    }
    return _this;
}
 
function Teacher(name) {
    // body...
    var _this = Person(name);
    var superSay = _this.sayHello;
    _this.sayHello = function(argument) {
        superSay.call(_this);
        alert("T_hello" + _this._name);
    }
    return _this;
}
 
var t = Teacher("aaaa");
//console.log(t);
t.sayHello();

196558-20160726165921388-1755259353.gif

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值