2012-02-23 62 views
0

我有脚本...为什么我无法将属性绑定到使用原型的对象?

var MyClass = { 
     someText: 'Hello World' 
    }; 


    jQuery(document).ready(function() { 

     console.log(MyClass.someText); 
     MyClass.prototype.someText = 'proto Hello World'; 
     console.log(MyClass.someText); 

    }); 

但我得到一个异常说...

Microsoft JScript runtime error: `MyClass.prototype is null or not an object` 

但是,当我读到原型它说,它向缴费对象的所有实例,但以上似乎反驳了这一点。 Whagwan?

+0

是什么'的console.log(MyClass的);'给你? – 2012-02-23 11:50:56

回答

4

为什么我的JavaScript不工作?

因为你不明白原型是如何工作的。函数定义原型,对象继承。

var MyClass = function() { }; 
MyClass.someText = 'Hello World'; 
MyClass.prototype.someText = 'proto Hello World'; 

要得到继承原型属性或方法的对象,你需要创建一个实例:

var myInstance = new MyClass(); 
console.log(myInstance.someText); 

您也可以与特定的内部[[原型]]创建一个对象通过使用ES 5方法Object.create()

var myObj = Object.create({someText: 'proto Hello World'}); 
console.log(myObj.someText); 
1

如果你创建MyClass的对象是这样的:

var MyClass = function() {}; 

然后原型自动创建。

0

试试这个

VAR MyClass的= { someText: '你好世界' };

jQuery的(文件)。就绪(函数(){

 console.log(MyClass.someText); 
     MyClass.someText = 'proto Hello World'; 
     console.log(MyClass.someText); 

}); 

var MyClass = function() { }; 
    MyClass.someText = 'Hello World'; 
    MyClass.prototype.someText = 'proto Hello World'; 
0

你不需要在这种情况下,.prototype:

var MyClass = {  someText: 'Hello World' }; 
alert (MyClass.someText); 
MyClass.someText = 'proto Hello World'; 
alert (MyClass.someText); 

会提醒“Hello World”和“proto Hello World”

编辑:我想跟进一些有用的信息 - 不是真的超级新,但也许这将有助于成功的人。

一些背景资料:http://ejohn.org/blog/simple-class-instantiation/

工作例如:http://jsfiddle.net/MarkSchultheiss/4GZha/#base

// makeClass - By John Resig (MIT Licensed) 

function makeClass() { 
    return function(args) { 
     if (this instanceof arguments.callee) { 
      if (typeof this.init == "function") this.init.apply(this, args.callee ? args : arguments); 
     } else return new arguments.callee(arguments); 
    }; 
} 
var MyClass = makeClass(); 
MyClass.prototype.init = function(newText, newThing) { 
    this.someText = newText == undefined ? 'defaultText' : newText; 
    this.newThing = newThing == undefined ? 'defaultThing' : newThing ; 
; 
    this.gobble = 'turkey'; 
    this.cracker = 'cheese'; 
} 

MyClass.prototype.otherText = 'otherstuff'; 
var trustme = MyClass('trustmedude'); 
alert(trustme.someText +":"+ trustme.newThing); 
var iam = MyClass('some new text', 'mything'); 
alert("tmething "+trustme.newThing); 
alert(iam.someText); //returns "some new text" 
iam.someText = 'hi fred'; 
alert(iam.someText); //returns "some ne text" 
alert(iam.otherText); // returns "otherstuff" 
alert(iam.newThing); //returns "mything" 
alert(MyClass.someText); //returns undefined 
alert(MyClass.otherText); //returns undefined 
alert(iam.cracker + iam.gobble); //returns "cheeseturkey" 
alert(iam.hasOwnProperty("someText")); //returns true 
相关问题