浅谈JavaScript 覆盖原型以及更改原型
作者:jingxian 时间:2024-04-10 10:51:12
覆盖原型
//囚犯示例
//1.定义原型对象
var proto = {
sentence : 4, //监禁年限
probation: 2 //缓刑年限
};
//2.定义原型对象的构造函数
var Prisoner = function(name, id) {
this.name = name;
this.id = id;
};
//3.将构造函数关联到原型
Prisoner.prototype = proto;
//4.实例化对象——采用工厂函数实例化对象
var makePrisoner = function(name, id) {
//采用工厂函数实力化对象prisoner
var prisoner = Object.create( proto );
prisoner.name = name;
prisoner.id = id;
return prisoner;
};
var firstPrisoner = makePrisoner( 'Joe', '12A' );
//firstPrisoner.sentence在firstPrisoner对象找不到sentence属性,
//所以查找对象的原型并找到了Both of these output 4
console.log( firstPrisoner.sentence );
console.log( firstPrisoner.__proto__.sentence );
//把对象的sentence属性设置为10
firstPrisoner.sentence = 10;
//outputs 10
//确定对象上的属性值已设置为10
console.log( firstPrisoner.sentence );
//但是对象的原型并没有变化,值仍然为4
console.log( firstPrisoner.__proto__.sentence );
//为了使获取到的属性回到原型的值,将属性从对象上删除
delete firstPrisoner.sentence;
//接下来,JavaScript引擎在对象上不能再找到该属性,
//必须回头去查找原型链,并在原型对象上找到该属性
// Both of these output 4
console.log( firstPrisoner.sentence );
console.log( firstPrisoner.__proto__.sentence );
ubuntu 终端node输出
xxh@xxh-E440:~/workspace$ node t6
4
4
10
4
4
4
那么如果改变了原型对象的属性值,会发生什么呢?我知道你在思考。
标签:javascript,覆盖
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python解析基于xml格式的日志文件
2022-11-08 21:26:31
![](https://img.aspxhome.com/file/2023/6/107216_0s.jpg)
mysql prompt的用法详解
2024-01-28 07:30:32
Python学习之流程控制与条件判断总结
2023-08-20 13:37:02
![](https://img.aspxhome.com/file/2023/8/70148_0s.jpg)
pd.to_datetime中时间object转换datetime实例
2021-09-23 19:22:15
Tensorflow中tf.ConfigProto()的用法详解
2022-01-12 03:33:25
Python 在局部变量域中执行代码
2023-06-12 04:57:15
vue实现购物车功能(商品分类)
2023-07-02 16:34:30
python实现dnspod自动更新dns解析的方法
2021-10-24 14:19:47
Python文件的操作示例的详细讲解
2023-11-20 17:54:55
![](https://img.aspxhome.com/file/2023/8/133398_0s.png)
js事件委托和事件代理案例分享
2024-04-28 09:51:31
Python将多份excel表格整理成一份表格
2022-06-11 13:54:50
Python学习之书写格式及变量命名
2023-08-23 14:53:08
浅谈Python flask框架
2021-04-07 00:45:43
![](https://img.aspxhome.com/file/2023/7/85257_0s.png)
asp数组去重复和数组排序
2008-10-30 12:51:00
python函数的两种嵌套方法使用
2022-01-14 08:06:58
浅谈Python中文件夹和python package包的区别
2021-03-23 21:57:26
![](https://img.aspxhome.com/file/2023/6/64326_0s.jpg)
Python排序算法之堆排序算法
2023-01-17 02:00:55
![](https://img.aspxhome.com/file/2023/3/63933_0s.png)
关于ASP eof与bof 区别分析
2011-03-11 11:14:00
Pycharm 操作Django Model的简单运用方法
2022-05-09 14:07:15
![](https://img.aspxhome.com/file/2023/9/110259_0s.jpg)
Pytorch Tensor的索引与切片例子
2022-12-08 16:28:10