Javascript 未定义原型而创建的新对象
我正在开发一个笛卡尔坐标库,我试图简单地创建一个类,定义原型并创建实例 但在这个简单的例子中,我的笛卡尔对象没有任何方法Javascript 未定义原型而创建的新对象,javascript,object,prototype,Javascript,Object,Prototype,我正在开发一个笛卡尔坐标库,我试图简单地创建一个类,定义原型并创建实例 但在这个简单的例子中,我的笛卡尔对象没有任何方法 let Cartesian = function(instance, opts) { let pos = opts.pos || {x:0, y: 0} /* .. Logic here .. */ return {pos: pos} } console.log("Before : ", Cartesian.prototype.getPosition) Car
let Cartesian = function(instance, opts) {
let pos = opts.pos || {x:0, y: 0}
/* .. Logic here .. */
return {pos: pos}
}
console.log("Before : ", Cartesian.prototype.getPosition)
Cartesian.prototype.getPosition = function() {
return true
}
console.log("After : ", Cartesian.prototype.getPosition)
CartesianExport = {
create: function (instance, opts) {
console.log("Create new : ", Cartesian.prototype.getPosition)
let c = new Cartesian(instance, opts)
console.log("Created : ", c, c.getPosition)
return c
}
}
module.exports = CartesianExport
这是我的安慰
Before : undefined
After : function () { return true }
Create new : function () { return true }
Created : Object {pos: Object} undefined
我不明白为什么我在尝试使用时得到了笛卡尔函数。getPosition不是一个函数。使用此函数:
function Cartestian(opts) {
this.pos = opts.pos || {x: 0, y: 0};
}
当你说返回{pos:pos}
在构造函数中,将返回无原型对象{pos:pos}
,而不是笛卡尔
的新实例。实例将被返回值覆盖。因此,新笛卡尔(…)
计算为一个没有原型的对象。这就是我的意思:
function IncorrectlyDefined(obj) {
return obj;
}
var someObj = {x: 0, y: 0};
var x = new IncorrrectlyDefined(someObj);
// x === someObj
没有cartesian.getPosition函数的声明,这只是您的未定义。所以你可以声明函数c.getPosition函数,你可以在
Cartesian
-return{pos:pos}
中得到它?我想你误解了Javascript构造函数的工作原理。在我的例子中,我返回其他属性,我可以从c.pos
访问。在这种情况下,返回的对象不是Cartesian
,即return
语句丢弃了构造函数正在构造的对象。@Arthur你可以返回这个,但通常情况下,您将不返回任何内容,并允许自动使用此
。规则是,除非返回不同的对象,否则构造函数将始终返回您创建的此
对象。要在新对象上获取类原型,必须在构造函数上返回this