如何解决关于Object.create和javascript中“ new”方法的输出的问题
最近,我了解了原型,“原型”和继承的概念。 我试图找出下面的输出,但是失败了……
function test(){
var a = 1;
this.b =2;
}
var o1 = new test();
var o2 = Object.create(test);
console.log(test.a); //undefined
console.log(test.b); //undefined
console.log(o1.a); //undefined
console.log(o1.b); //2
console.log(o2.a); //undefined
console.log(o2.b); //undefined
作为javascript新秀,有人可以告诉我
为什么只有“ o1.b”可以访问值2?
解决方法
首先,您在这里做错了一些事情。让我分解一下。在每一行之后查看注释。
function test(){
var a = 1; //this variable a is local to this function test only.so it is not part of the o1,o2 objects.
this.b =2; //this keyword refers to the object on which this function is called.
}
var o1 = new test();
var o2 = Object.create(test);//this is not a way to create object using Object.create().. Object.create() takes another object as an argument to create a new object and here you are using test which is a function.
console.log(test.a); //test is a function not an object
console.log(test.b); //test is a function not an object
console.log(o1.a); //since a is local to the function that's why you are getting undefined here
console.log(o1.b); //here output is 2 because b is an object property and you have assigned its value to 2 in the test function.
console.log(o2.a); //undefined because o2 is not an object it is a function.
console.log(o2.b); //undefined because o2 is not an object it is a function.
您可以尝试以这种方式实现上面的代码:
var Test=function test(){
this.a = 1;
this.b =2;
}
var o1 = new Test();
var o2 = Object.create(o1);
console.log(o1.a);
console.log(o1.b);
console.log(o2.a);
console.log(o2.b);
,
在javascript函数中,对象也是对象,因此test
,o1
和o2
是对象,它们具有属性,这是在控制台上可视化时的结果:
console.log(test.a); //undefined ---> test has no a nor b property
console.log(o1.b); //2 ---> o1 has b property
console.log(o2.a); //undefined ---> o2 has no a nor b property
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。