学习笔记:JS面向对象之包装对象-原型链

js是基于原型的程序

例:使用Array.prototype.push = function(){}可以更改array的push方法
未免代码混乱不要轻易修改

包装对象:基本类型都有自己的包装对象:String Number Boolean
var str = new String('hello');此处的str是对象类型,即字符串形式的对象
var str = 'hello中,基本类型会找到对应的包装对象类型,包装对象把所有的属性和方法给了基本类型之后消失。所以基本类型虽然不是对象,也能使用方法。
给字符串添加方法:

var str = 'hello';
String.prototype.lastValue = function () {
    return this.charAt(this.length);
}
//添加在原型下,方法共享
alert(str.lastValue());

而下面这种写法,返回的则是undefined

var str = 'hello';
str.number = 10;
alert(str.number);

str.number=10给str添加属性的时候,str返回去找包装对象,赋给str之后该包装对象消失。在遇到alert(str.number)时,str回去找包装对象,但是原包装对象已消失,所以创建了一个新的包装对象加入属性number,故此处的属性number未定义


原型链:实例对象与原型之间的连接

function Test() {
    this.num = 10;
}
Test.prototype.num = 10;
var t1 = new Test();
alert(t1.num);
//返回10

此时t1有属性num,直接找到num=10

function Test() {
}
Test.prototype.num = 20;
//num挂载到构造函数的原型下面
var t1 = new Test();
alert(t1.num);
//返回10

t1下面没有num属性,于是通过隐式链__proto__找到原型Test.prototype,再往下找到属性num=20

原型链的最外层:Object.prototype

function Test() {
}
Object.prototype.num = 30;
//num挂载到构造函数的原型下面
var t1 = new Test();
alert(t1.num);
//返回30

此时t1和Test.prototype都没有属性num,找到Object.prototypenum=30
流程示意图如下
这里写图片描述


猜你喜欢

转载自blog.csdn.net/weixin_38623747/article/details/81535993