有关原型与原型链的面试题目

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011435776/article/details/80904837
//有关原型与原型链的面试题目
{
	function Fn(){
		this.x = 100;
		this.y = 200;
		this.getX = function () {
			console.log(this.x);
		}
	}
	Fn.prototype.getX = function () {
		console.log(this.x);
	};
	Fn.prototype.getY = function () {
		console.log(this.y);
	};
	var f1 = new Fn;
	var f2 = new Fn;
	console.log(f1.getX === f2.getX);	//false
	console.log(f1.getY === f2.getY);	//true
	console.log(f1.__proto__.getY === Fn.prototype.getY);	//true
	console.log(f1.__proto__.getX === f2.getX);		//false
	console.log(f1.__proto__.getX === Fn.prototype.getX);	//true
	console.log(f1.constructor);	//Fn
	console.log(Fn.prototype.__proto__.constructor);	//Object
	f1.getX();	//100	this=>f1
	f1.__proto__.getX();	//undefined 	this=>f1.__proto__(Fn.prototype)
	f2.getY();	//200	this=>f2
	Fn.prototype.getY();	//undefined	this=>f2.__proto__(Fn.prototype)
}
// false,true,true,false,true,Fn,Object,100,undefined,200,undefined


      

// 原型、原型链
{
	function fun(){
		this.a = 0;
		this.b = function(){
			console.log(this.a);
		}
	}
	fun.prototype = {
		b: function(){
			this.a = 20;
			console.log(this.a);
		},
		c: function(){
			this.a = 30;
			console.log(this.a);
		}
	}
	var my_fun = new fun();
	my_fun.b();	//私有方法	this=>my_fun
	console.log(my_fun.a);
	my_fun.c();	//公有方法	this=>my_fun this.a = 30(将私有属性a修改为30)
	console.log(my_fun.a);
	var my_fun2 = new fun();
	console.log(my_fun2.a);
	my_fun2.__proto__.c();	//this=>my_fun2.__proto__ 当前实例通过原型链在类的共有属性上增加了一个a:30
	console.log(my_fun2.a);
	console.log(my_fun2.__proto__.a);
}
// 0,0,30,30,0,30,0,30

         prototype.js

没有更多推荐了,返回首页