没有合适的资源?快使用搜索试试~ 我知道了~
JAVASCRIPT 面向对象编程.docx
需积分: 0 1 下载量 143 浏览量
2019-06-18
15:03:09
上传
评论
收藏 68KB DOCX 举报
温馨提示
试读
21页
从一个整体的角度来说明一下Javascript的面向对象的编程。
资源推荐
资源详情
资源评论
JAVASCRIPT 面向对象编程
是一个类 的语言,他的面向对象的东西相对于
比较奇怪,但是其的确相当的强大,在 同学 的“对象的消息
模型”一文中我们已经可以看到一些端倪了。这两天有个前同事总在问
我 面向对象的东西,所以,索性写篇文章让他看去吧,这
里这篇文章主要想从一个整体的角度来说明一下 的面向对
象的编程。另,这篇文章主要基于,旨在介绍新技术。
关于兼容性的东西,请看最后一节。
初探
我们知道 中的变量定义基本如下:
1
2
3
var name = 'Chen Hao';;
var email = 'haoel(@)hotmail.com';
var website = 'https://coolshell.cn';
如果要用对象来写的话,就是下面这个样子:
1
2
3
4
5
var chenhao = {
name :'Chen Hao',
email : 'haoel(@)hotmail.com',
!!!!website : 'https://coolshell.cn'
};
于是,我就可以这样访问:
1
2
//以成员的方式
chenhao.name;
3
4
5
6
7
8
9
chenhao.email;
chenhao.website;
//以 hash map 的方式
chenhao["name"];
chenhao["email"];
chenhao["website"];
关于函数,我们知道 的函数是这样的:
1
2
3
var doSomething = function(){
alert('Hello World.');
};
于是,我们可以这么干:
1
2
3
4
5
6
7
8
9
1
0
1
1
var sayHello = function(){
!!!var hello = "Hello, I'm "+ this.name
!!!!!!!!!!!!!!!!+ ", my email is: " + this.email
!!!!!!!!!!!!!!!!+ ", my website is: " + this.website;
alert(hello);
};
//直接赋值,这里很像 C/C++的函数指针
chenhao.Hello = sayHello;
chenhao.Hello();
相信这些东西都比较简单,大家都明白了。可以看到 对象
函数是直接声明,直接赋值,直接就用了。 的动态语言。
还有一种比较规范的写法是:
1
2
3
4
5
6
//我们可以看到, 其用 function 来做 class。
var Person = function(name, email, website){
this.name = name;
this.email = email;
this.website = website;
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
this.sayHello = function(){
!!!!!!!!var hello = "Hello, I'm "+ this.name! + ", \n" +
!!!!!!!!!!!!!!!!!!!!"my email is: " + this.email + ", \n" +
!!!!!!!!!!!!!!!!!!!!"my website is: " + this.website;
alert(hello);
};
};
var chenhao = new Person("Chen Hao", "haoel@hotmail.com",
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"https://coolshell.cn");
chenhao.sayHello();
顺便说一下,要删除对象的属性,很简单:
1delete chenhao['email']
上面的这些例子,我们可以看到这样几点:
1. 的数据和成员封装很简单。没有类完全是对象操作 。
纯动态!
2. 中的 指针很关键,如果没有的话,那
就是局部变量或局部函数。
3. 对象成员函数可以在使用时临时声明,并把一个全
局函数直接赋过去就好了。
4. 的成员函数可以在实例上进行修改,也就是说不同
实例相同函数名的行为不一定一样。
属性配置–Object.deneProperty
先看下面的代码:
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
//创建对象
var chenhao = Object.create(null);
//设置一个属性
Object.defineProperty( chenhao,
'name', { value: 'Chen Hao',
writable: true,
configurable: true,
!!!!!!!!!!!!!!!!!!!!!!!!!!enumerable:!! true });
//设置多个属性
Object.defineProperties( chenhao,
{
!!!!!!!!'email'! : { value:! 'haoel@hotmail.com',
writable: true,
configurable: true,
!!!!!!!!!!!!!!!!!!!!!enumerable:!! true },
!!!!!!!!'website': { value: 'https://coolshell.cn',
writable: true,
configurable: true,
!!!!!!!!!!!!!!!!!!!!!enumerable:!! true }
}
);
剩余20页未读,继续阅读
资源评论
weixin_42582820
- 粉丝: 0
- 资源: 8
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功