原型的一些知识
普通调用函数,若函数没有return语句,等于return undefined,
构造函数调用的时候,1创建一个新对象,2将构造函数的作用域赋给新对象(this赋给了这个新对象),3执行构造函数中的代码(为这个新对象添加属性),4返回新对象
function A(){
//1这一步是看不到的,创建一个新对象;
var a = {};
//2第二步赋给新对象。
this = a;
//3执行
alert(this);
//4返回新对象
return this;
}
A.prototype.a = 1;
console.log(new A().a);
1 2 3 4 5 6 7 8 9 10 11 12 13 | function A() { alert(this); return {a: 'a'}; } A.prototype.a = 1; console.log(new A().a);< br >new A()与原型没关系,因为返回的不是this,是自己返回的对象的属性a;, |
1 2 3 4 5 6 7 8 9 10 11 12 | function Human() { } Human.prototype.address = { country: 'China', province: 'Zhejiang' }; var h = new Human(); h.address.country = 'US'; alert(h.address.country); //US,实例覆盖了原型,在实例上 alert(h.address.province); //Zhejiang,原型上 alert(h.hasOwnProperty('address')); //false |
1 2 3 4 5 6 7 8 9 | h.address = { country: 'US' }; delete h.address.country; delete h.address; alert(h.address.country); //US,实例覆盖了原型,在实例上 alert(h.address.province); //Zhejiang,原型上 alert(h.hasOwnProperty('address')); //false |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function Human() { } Human.prototype.address = { country: 'China', province: 'Zhejiang' }; var h = new Human(); Human.prototype = { address: { a: 'aaa' } }; var h2 = new Human(); alert(h.address.country); //China alert(h.address.province); //Zhejiang alert(h.address.a); //undefined alert(h2.address.country); //undefined alert(h2.address.province); //undefined alert(h2.address.a); //aaa |
1 2 3 4 5 6 7 8 9 10 11 12 | function test(h1) { h1 = {}; h1.address = { a: 'aaa' }; // address.a = 'bbb'; } test(h); alert(h.address.country); //China alert(h.address.province); //Zhejiang alert(h.address.a); //undefined |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var a = 'a'; function test(a) { alert(a); //a a = 'b'; alert(a); //b test2(a); } function test2(b) { // var a; alert(b); //b alert(a); //b // a = 'c'; alert(a); //c } test(a); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | var getName; function getName() { return 5; } function Foo() { getName = function () { return 1; }; return this; } Foo.getName = function () { return 2; }; Foo.prototype.getName = function () { }; getName = function () { return 4; }; //请写出以下输出结果: console.log(Foo.getName()); console.log(getName()); console.log(Foo().getName()); console.log(getName()); console.log(new Foo.getName()); console.log(new Foo().getName()); var f = new new Foo().getName(); alert(f); |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步