javascript 无法获取未定义或空引用的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15598231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to get property of undefined or null reference
提问by Mahesha999
I am getting following error
我收到以下错误
Unable to get property 'showMsg' of undefined or null reference
无法获取未定义或空引用的属性“showMsg”
on the last line of below code:
在下面代码的最后一行:
Function.prototype.showMsg = function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
var personObj = new Person();
personObj.prototype.showMsg();
Actually I should be able to access showMsg()
from Person
instance since I have added it to the Function.prototype
. Then why I am getting this error?
实际上我应该能够showMsg()
从Person
实例访问,因为我已将它添加到Function.prototype
. 那为什么我会收到这个错误?
采纳答案by Marwan
Well You Understand it all Wrong
好吧,你完全理解错了
Function.prototype.showMsg = function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
var personObj = new Person();
personObj.prototype.showMsg();
First you prototyped the function class, then create a custom class called Person, then you create an instance of Person. And then you are calling the very blue print which is showMsg which is 2 Mistakes 1 showMsg is not Bounded into the Person and then to call it if its bounded you call it directly like this
首先创建函数类的原型,然后创建一个名为 Person 的自定义类,然后创建 Person 的实例。然后你正在调用非常蓝图,它是 showMsg,这是 2 个错误 1 showMsg 没有绑定到 Person 中,然后调用它,如果它有界,你直接像这样调用它
personObj.showMsg()
Will To Make This Script Work from my point of View if i got you write write it like this ->
如果我让你这样写的话,我会从我的角度让这个脚本工作 ->
function Person() {
this.name = "Mahesh";
};
Person.prototype.showMsg = function () {
alert("This is a sample message.");
};
var personObj = new Person();
personObj.showMsg();
my script bound the showMsg Directly to the Person Class if you need it through the Person Object and Through The Function Class To Then you have to inherit from Function Class Like This
我的脚本将 showMsg 直接绑定到 Person 类,如果你需要它通过 Person 对象和通过函数类 To 然后你必须像这样从函数类继承
Function.prototype.showMsg=function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
Person.prototype = Function;
Person.prototype.constructor = Person;
var personObj = new Person();
personObj.showMsg();
Regards
问候