【发布时间】:2014-04-21 03:16:47
【问题描述】:
我正在尝试让您更好地了解 JavaScript,尤其是原型功能。我遇到了这种情况:
我正在尝试使用类型函数定义一个函数 someObject ,以便它的行为如下所示:
var myTestObject = someObject();
如果我打电话:
myTestObject() ===> "The object is initailType"
然后当它被调用时
myTestObject.type() ===> "InitialType"
如果我打这个电话
myTestObject.type("newtype")
myTestObject.type() ===> "newType"
来电
myTestObject() ===> "The Object is newType".
How does JavaScript .prototype work?这两个我都试过了
还有这个How do you create a method for a custom object in JavaScript?
,但是我得到了几个不同的错误,这取决于它是如何实现的,尽管大部分都是这样(Uncaught TypeError: Object myTestObject has no method 'type')。我觉得我让这件事变得更难了。
编辑:更多代码。
function box(){
var _current = "initialType"
Object.defineProperty(this, "current", {
get: function(){return _current;},
set: function(value){
if(arguments.length === 1){
_current = value;
} }
})
return "The Object is " + this.type(this.current)
}
box.prototype.type = function(newValue){
var type = null;
if(arguments.length == 0){
type = "initialType";
}else {
type = newValue
}
return type
}
【问题讨论】:
-
您应该发布完整的代码。我猜你应该使用 myTestObject.prototype.type = function() { } 来定义类型,但是类型函数也可能有问题。
标签: javascript