这是一个非常激烈的问题,但我认为其原因在于缺乏有关此主题的良好文档和优秀书籍。javaScript中的对象,原型和构造函数
当我学习一门语言时,即使我的一些测试是荒谬的,我也会进行大量的挖掘,但我认为了解事物的唯一途径就是做各种实验。
我以JavaScript开始,尽可能多的代码,我更困惑。
让我们查看代码(现在忘了没有感觉,只考虑了输出):
function Vehicle()
{
this.color = 'Blue'
}
var car = new Vehicle()
console.log('Vehicle.constructor: ', Vehicle.constructor)
console.log('car.constructor: ', car.constructor)
console.log('Vehicle.prototype: ', Vehicle.prototype)
console.log('car.prototype: ', car.prototype)
console.log('Vehicle.constructor.prototype: ', Vehicle.constructor.prototype)
console.log('car.constructor.prototype: ', car.constructor.prototype)
console.log('Vehicle.prototype.constructor: ', Vehicle.prototype.constructor)
console.log('car.prototype.constructor: ', car.prototype.constructor)
Output:
Vehicle.constructor: Function()
car.constructor: Vehicle()
Vehicle.prototype: Vehicle {} // curly braces here
car.prototype: undefined
Vehicle.constructor.prototype: function()
car.constructor.prototype: Vehicle {} // curly braces here
Vehicle.prototype.constructor: Vehicle()
TypeError: car.prototype is undefined
我的结论:
Vehicle.prototype == == car.constructor.prototype车辆{} //这里花括号
Vehicle.prototype.constructor == car.constructor ==车辆()//括号这里
Vehicle.constructor ==功能()//大写 'F'
Vehicle.constructor.prototype ==函数()//小写 'F'
car.prototype ==未定义未定义//但没有报告作为误差
car.prototype.constructor //类型错误。这里car.prototype'被报告为错误
现在让我们考虑类似的代码:
var car = {color: 'Blue'}
console.log('car.constructor: ', car.constructor)
console.log('car.prototype: ', car.prototype)
console.log('car.constructor.prototype: ', car.constructor.prototype)
console.log('car.prototype.constructor: ', car.prototype.constructor)
Output:
car.constructor: Object()
car.prototype: undefined
car.constructor.prototype: Object {} // curly braces here
TypeError: car.prototype is undefined
我们可以看到,这里的car.prototype'是只有不确定的,但“车.prototype.constructor'是未定义的,并且也是'TypeError'
上面的代码在Firebug中进行了测试。我不知道这是Firebug的错误或JavaScript错误。
所有这一切都让我感到困惑。
如果这是OOP在JavaScript中,我认为这是更ODP - 面向对象(DIS)编程
编辑
1)为什么car.prototype是不确定时car.prototype。构造函数是TypeError
2)为什么函数和对象都有构造函数和原型(参见上面的代码)?
3)。这是什么意思:
Vehicle.constructor.prototype:函数()
Vehicle.prototype.constructor:车辆()
car.constructor。原型:车辆{}
我很难理解你的问题。你到底在问什么?我们可以回答“原型和构造函数之间有什么区别”或者“为什么x.y.z给出TypeError时x.y没有定义”,但是你没有问任何特定的问题。对我来说,最好的办法是找到关于JavaScript的函数,原型和构造函数的好文章,并理解它们之间的关系。你可以尝试[this](http://www.codeproject.com/Articles/687093/Understanding-JavaScript-Object-Creation-Patterns),尽管还有其他无数人。 – Avish
基本上我不明白原型和构造者是如何不同的,为什么我们既可以与对象和函数相关联,也可以使用object.prototype.constructor(或反函数) – user3244003