2012-02-23 56 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 
相關問題