代码一:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script> function Car (desc) { this.desc = desc; this.color = "red"; } // Car.prototype = { // getInfo: function() { // return 'A ' + this.color + ' ' + this.desc + '.'; // } // }; //instantiate object using the constructor function var car=new Car("bmw"); // var car = Object.create(Car.prototype); // console.log(car.getInfo()); console.log(car instanceof Car); console.log(car.color); console.log(car.desc); </script> </head> <body> </body> </html>
以上code输出结果为:
true
red
bmw
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
function Car (desc) {
this.desc = desc;
this.color = "red";
}
// Car.prototype = {
// getInfo: function() {
// return 'A ' + this.color + ' ' + this.desc + '.';
// }
// };
//instantiate object using the constructor function
// var car=new Car("bmw");
var car = Object.create(Car.prototype);
// console.log(car.getInfo());
console.log(car instanceof Car);
console.log(car.color);
console.log(car.desc);
</script>
</head>
<body>
</body>
</html>
以上code输出结果:
true
undefined
undefined
问题来了:
通过new+构造函数构建实例,实例能访问构造函数的属性
通过Object.create(prototype)构建实例时,实例对象不能访问构造函数的属性
以上结果出现的理论依据在哪里。找出来