想知道自己Js原型与原型链掌握的怎么样?来做个题试试吧!
Js原型与原型链图示:

问题集锦:
问题1:
var A = function() {}; A.prototype.n = 1; var b = new A(); A.prototype = { n: 2, m: 3 } var c = new A();
console.log(b.n); console.log(b.m);
console.log(c.n); console.log(c.m);
|
答案1:
b.n -> 1 b.m -> undefined;
c.n -> 2; c.m -> 3;
|
问题2:
var F = function() {};
Object.prototype.a = function() { console.log('a'); };
Function.prototype.b = function() { console.log('b'); }
var f = new F();
f.a(); f.b();
F.a(); F.b();
|
答案2:
f.a() -> a f.b() -> f.b is not a function
F.a() -> a F.b() -> b
|
问题3:
function Person(name) { this.name = name } let p = new Person('Tom');
|
问题1: p.__proto__
等于什么?
问题2:Person.__proto__
等于什么?
答案3:
答案1:Person.prototype
答案2:Function.prototype
问题4:
var foo = {}, F = function(){}; Object.prototype.a = 'value a'; Function.prototype.b = 'value b';
console.log(foo.a); console.log(foo.b);
console.log(F.a); console.log(F.b);
|
答案4:
foo.a => value a foo.b => undefined F.a => value a F.b => value b
|
问题5:
function Fn() { var num = 500; this.x = 100; } Fn.prototype.getX = function () { console.log(this.x); } Fn.aaa = 1000;
var f = new Fn;
console.log(f.num) console.log(f.aaa) var res = Fn(); console.log(res)
|
答案5:
f.num => undefined f.aaa => undefined var res = Fn();
|
问题6:一个灵魂面试题
function Person(name) { this.name = name } var p2 = new Person('king');
console.log(p2.__proto__) console.log(p2.__proto__.__proto__)
console.log(p2.__proto__.__proto__.__proto__)
console.log(p2.__proto__.__proto__.__proto__.__proto__)
console.log(p2.__proto__.__proto__.__proto__.__proto__.__proto__)
console.log(p2.constructor) console.log(p2.prototype)
console.log(Person.constructor) console.log(Person.prototype)
console.log(Person.prototype.constructor) console.log(Person.prototype.__proto__)
console.log(Person.__proto__)
console.log(Function.prototype.__proto__) console.log(Function.__proto__)
console.log(Object.__proto__) console.log(Object.prototype.__proto__)
|
问题7:
function A() { B = function () { console.log(10) } return this }; A.B = function () { console.log(20) }; A.prototype.B = function () { console.log(30) }; var B = function () { console.log(40) }; function B() { console.log(50) }
console.log(A.B()) console.log(B()) console.log(A().B()) console.log(B()) console.log(new A.B()) console.log(new A().B())
|
答案7解析:
A.B()
B()
A().B()
B()
new A.B()
new A().B()
|
未完待续。。。