Understand 6 questions about JavaScript prototype and prototype chain, the interviewer can't help but feel sorry for you!

 

Description:

In JavaScript, an object has a __proto__ attribute (implicit prototype), which points to the prototype of the constructor function that constructed the object.

The function Function is special. In addition to having __proto__ attributes like other objects, it also has its own unique attributes—prototype is called the prototype object. The prototype object has a constructor attribute, which points back to the function.

Classic picture:

 

Next are a few questions I organized, I hope to help you!

Topic 1:

function F() {
  this.a = 1;
}
var obj = new F();
console.log(obj.prototype);//打印undefined   对象只有 __proto__属性没有prototype属性,函数才有

Topic 2:

Object.prototype.a = 1;
var obj = {
    b: 2
};
for(var i in obj) {
    console.log(i); //能迭代出原型链里面的属性,所以会打印出 b和a
}

Question 3:

Object.prototype.a = 1; 
var obj = {
    b: undefined
};

console.log(obj.a);//1
console.log('b' in obj);//true  //能找到处于原型链里面的bar属性

console.log(obj.hasOwnProperty('a'));//false 不是自身的属性
console.log(obj.hasOwnProperty('b'));//true  是自身的属性

Question 4:

function A(){
}
function B(a){
  this.a = a;
}
function C(a){
  if(a){
		this.a = a;
  }
}
A.prototype.a = 1;
B.prototype.a = 1;
C.prototype.a = 1;
 //实例对象都能访问构造函数的原型对象,可以明确的是以上3个都是能拿到a的
 
console.log(new A().a);//1   拿到的是原型上的a=1
console.log(new B().a);//undefined  this.a = a;将new B()这个实例对象的a属性这是为undefined,所以拿到的是undefined
console.log(new C(2).a);//2   将new C(2)这个实例对象的a属性这是为2,所以拿到的是2

Question 5:

function A () {
}
A.prototype.n = 1;

var b = new A();//b实例对象已经建立原型连接

//原型对象指向被改变,不会切断b实例对象的
A.prototype = {
    n: 2,
    m: 3
}
var c = new A();//c实例对象将根据新的原型建立连接

console.log(b.n, b.m); //1 undefined  这里拿到是改变prototype之前的
console.log(c.n, c.m); //2 3		这里拿到是改变prototype之后的

Question 6:

var F = function(){};
Object.prototype.a = function(){
    console.log('a')
}
Function.prototype.b = function(){
    console.log('b')
}
var f = new F();

F.a();  //打印a  对象都能访问Object.prototype中的属性和方法
F.b();  //打印b  F是函数,原型链  F => F.__proto__ => Function.prototype => Function.prototype.__proto__ => Object.prototype

f.a();  //打印a  对象都能访问Object.prototype中的属性和方法
f.b();  //报错f.b is not a function   因f是F实例对象,原型链 f=>f.__proto__=>F.prototype=>F.prototype.__proto__ => Object.prototype

Please correct me! !

Guess you like

Origin blog.csdn.net/dkm123456/article/details/111885534