我尝试使用构造函数模式创建对象,并使用Object.defineProperty定义属性。
func panHandler(sender: UIPanGestureRecognizer)
{
guard let view = sender.view else{ return }
switch sender.state {
case .Began:
self.stackView.removeArrangedSubview(view)
self.view.addSubview(view)
let location = sender.locationInView(self.view)
view.center = location
case .Changed:
view.center.x += sender.translationInView(self.view).x
view.center.y += sender.translationInView(self.view).y
default:
view.removeConstraints(view.constraints)
view.translatesAutoresizingMaskIntoConstraints = true
// You can now set the view's frame or position however you want
view.center.x += sender.translationInView(self.view).x
view.center.y += sender.translationInView(self.view).y
}
sender.setTranslation(CGPointZero, inView: self.view)
}
抛出错误:Uncaught TypeError:object不是函数。 我做错了什么?请帮忙。
答案 0 :(得分:1)
有几个问题:
sample
sample
)上定义random
,但它应该在this
上。sample
,但您没有将其定义为一个函数。 defineProperty
中的函数是getter,而不是方法本身。如果你想这样编码,你需要getter来返回你的方法。使用注释检查此更正后的代码:
function random (a,b,c) {
var sample = null;
this.a = a;
// First define, then call:
// Define on this, not on random:
Object.defineProperty(this, 'sample', {
get: function() {
// must return a function
return function (b) {
console.log(b);
};
}
}); // <-- missing bracket
// Moved after defineProperty:
if(b && c) {
this.sample(b,c); // note that you don't use the second argument
}
}
console.log(new random(1,2,3));
&#13;