[英]Javascript prototype method “Cannot set property”
I'm always getting Cannot set property 'saySomething' of undefined but why?我总是得到无法设置未定义的属性 'saySomething'但为什么? Am I making a mistake somewhere?
我在某个地方犯了错误吗?
var Person = new Object();
Person.prototype.saySomething = function ()
{
console.log("hello");
};
Person.saySomething();
Debugging tip: You get this ..of undefined
errors when you try to access some property of undefined.调试提示:当您尝试访问 undefined 的某些属性时,您会收到此
..of undefined
错误。
When you do new Object()
, it creates a new empty object which doesn't have a prototype property.当您执行
new Object()
,它会创建一个没有原型属性的新空对象。
I am not sure what exactly are we trying to achieve here but you can access prototype of function and use it.我不确定我们到底想在这里实现什么,但您可以访问函数原型并使用它。
var Person = function() {}; Person.prototype.saySomething = function() { console.log("hello"); }; var aperson = new Person(); aperson.saySomething();
The prototype property exists on functions, not on instantiated objects.原型属性存在于函数上,而不是实例化对象上。
var Person = new Object(); console.log(Person.prototype); // undefined var Person2 = function () {} console.log(Person2.prototype); // {}
This is useful because things put on the prototype of a function will be shared by all object instances created with that function (by using new
).这很有用,因为放在函数原型上的东西将由使用该函数创建的所有对象实例共享(通过使用
new
)。
var Person = function() {}; Person.prototype.saySomething = function() { console.log("hello"); }; console.log( new Person().saySomething === Person.prototype.saySomething // true. they are the same function );
If all you want is to add a method to the person object, there's no need for a prototype:如果您只想向 person 对象添加一个方法,则不需要原型:
var Person = {}; Person.saySomething = function() { console.log("hello"); }; Person.saySomething();
You can even use object literal syntax:您甚至可以使用对象字面量语法:
var Person = { saySomething: function() { console.log("hello"); } }; Person.saySomething();
i was trying out some code thought of posting it, might help others.我正在尝试一些想发布它的代码,可能会帮助其他人。
<script>
var MODULE = {};
MODULE = (function (my) {
my.anotherMethod = function () {
console.log("hello ");
};
my.newMethod = function(){
console.log("hi new method ");
}
return my;
}(MODULE));
MODULE.anotherMethod();
MODULE.newMethod();
</script>
And please not var MODULE ={}, if this is not initialized with {} then it give cannot set property.并且请不要 var MODULE ={},如果它没有用 {} 初始化,那么它给出了无法设置的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.