Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

15. getName 以及所有涉及到 prototype 的题 #16

Open
fedono opened this issue Jul 8, 2020 · 2 comments
Open

15. getName 以及所有涉及到 prototype 的题 #16

fedono opened this issue Jul 8, 2020 · 2 comments
Labels

Comments

@fedono
Copy link
Owner

fedono commented Jul 8, 2020

问题

function Foo() {
  getName = function () { console.log (1); };
  return this;
}
Foo.getName = function () { console.log (2);};
Foo.prototype.getName = function () { console.log (3);};
var getName = function () { console.log (4);};
function getName() { console.log (5);}

//请写出以下输出结果:
Foo.getName();
getName();
Foo().getName(); 
getName();
new Foo.getName();
new Foo().getName();
new new Foo().getName();
@fedono
Copy link
Owner Author

fedono commented Jul 8, 2020

解答

参考

要点

new Foo.getName() 中因为没有执行Foo() 这个函数,所以会首先获取静态属性 Foo.getName() 执行
new Foo().getName() 中执行了 Foo() 函数,所以顺序是 (new Foo()).getName() ,那么就是获取原型上的getName() 函数

@fedono fedono added the JS label Aug 24, 2020
@fedono fedono changed the title 15. getName 15. getName 以及所有涉及到 prototype 的题 Apr 13, 2021
@fedono
Copy link
Owner Author

fedono commented Apr 13, 2021

写出以下的输出结果是什么

要注意的事,第二次中的 A.prototype 进行重写了

function A(){}
A.prototype.x = 10;

let a = new A();

A.prototype = {x: 20, y: 30};
let b = new A();

console.log(a.x);
console.log(a.y);
console.log(b.x);
console.log(b.y);

最后输出是

10
undefined
20
30

这时候打印

console.log(a.__proto__); // A { x: 10 }
console.log(b.__proto__); //  { x: 20, y: 30 }

如果不对 prototype 进行重写,也就是如下

function A(){}
A.prototype.x = 10;

let a = new A();

// A.prototype = {x: 20, y: 30};
A.prototype.y = 20;
let b = new A();

console.log(a.x);
console.log(a.y);
console.log(b.x);
console.log(b.y);

这时候打印

console.log(a.__proto__); //  A { x: 10, y: 20 }
console.log(b.__proto__); //  A { x: 10, y: 20 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant