原型链

原型链

原型链中没有找到返回undefined

同一个构造函数创造的的对象会有一块共用的内存

// 对象有__proto__,代表它的原型对象
// 函数有prototype属性,代表创建的对象的原型对象
// 任何函数包括自定义的函数,创建的__proto__ = Function.prototype
// 原型对象可以访问成员
var f1 = new Function('var a =20;console.log(a);arguments[0]');
f1(10,20);
function fn() {
    this.life = 1
}
// 隐式操作fn.prototype = {}
function fm() {
    this.color = 'black'
}
// 隐式操作fn.prototype = {}
var f1 = new fn();
var f2 = new fm();
console.log(f1.__proto__  === fn.prototype);	// true
console.log(f2__proto__ === f1__proto__)	// false

new 创建一个空对象,给它添加一个属性__ proto __这个属性(原型对象)

function fn() {
    this.a = 20;
}
function fm() {
    this.a = 30;
}
fm.prototpye.fn = new fn();
var f1 = new fm();
console.log(f1) // 画出它的内存示意
Function.prototype.life = 1;
function fn() {
    
}
var f1 = new fn();
console.log(f1.life) 
// undefined
       //25分
			function Parent() {
				this.a = 1;
				this.b = [1, 2, this.a];
				this.c = {
					demo: 5
				};
				this.show = function() {
					console.log(this.a, this.b, this.c.demo);
				}
			}
			function Child() {
				this.a = 2;
				this.change = function() {
					this.b.push(this.a);
					this.a = this.b.length;
					this.c.demo = this.a++;
				}
			}
			Child.prototype = new Parent();
			var parent = new Parent();
			var child1 = new Child();
			var child2 = new Child();
			child1.a = 11;
			child2.a = 12;


			parent.show();	// 1 [1,2,1] 5
			child1.show();	// 11 [1,2,1] 5
			child2.show();	// 12 [1,2,1] 5

			child1.change();
			child2.change();

			parent.show();	// 1 [1,2,1] 5
			child1.show();	// 5 [1,2,1,11,12] 5
			child2.show();	// 6 [1,2,1,11,12] 5

原型链的存取

构造函数的prototype属性可以操作,但不能修改,可以操作给原型属性添加成员

arr.prototype.push = 23;

对象__ proto__可以操作和修改,内置的对象不能修改

var arr = new Array(10,20,30);
arr.__proto__.fn = 90;
var arr2 = [10];
// 跳过编译(禁默),修改官方的,会导致错误,所以会禁默

取值操作:先取对象自己的,如果没有,则在__ proto__里取,知道null,如果都没有则取undefined

存储操作:a不管是不是原型链上的成员,都不能修改a,但如果a是原型链上的成员,可以修改a里面的数据

obj.a = 20;
// obj对象的原型链上无论有没有a的对象,都会在obj中添加或者修改
function fn() {
    
}
var f1 = new fn()
fn.prototype = {
    age:20
}
console.log(f1.age)
// undefined
function fn() {
    this.a = 'tom';
}
function fm() {}
fm.prototype = new fn();
function ff() {}
ff.prototyep = new fm();
var obj = new ff();
posted @ 2022-06-12 12:19  a立方  阅读(10)  评论(0编辑  收藏  举报