2016-06-15 73 views
-1
Object.someProp = "hello"; 
Object.prototype.somProp2 = "hello2"; 
var i = new Object(); 
alert(i.somProp2);//1 
alert(i.someProp);//2 

爲什麼1只能工作而不是2? 如果幾乎每個對象都是從「對象」派生的,那麼不應該像SomeProp2那樣沿着鏈條向下遍歷鏈。我對此很陌生,所以任何幫助都很好?爲什麼添加的對象屬性不能遍歷?

+0

對象實例繼承自* Object。原型*,而不是*對象*。 'i.someProp'應該返回* undefined *。 – RobG

回答

0

你好,請檢查下面

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo"></p> 

<script> 
function Person(first, last, age, eye) { 
    this.firstName = first; 
    this.lastName = last; 
    this.age = age; 
    this.eyeColor = eye; 
} 
Person.prototype.nationality = "English"; 
Person.nationality2 = "English"; 

var myFather = new Person("John", "Doe", 50, "blue"); 
document.getElementById("demo").innerHTML = 
"My father is " + myFather.nationality + myFather.nationality2; 
</script> 

</body> 
</html> 

的代碼,如果你運行它會告訴你我的父親是Englishundefined

但如果ü運行此

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo"></p> 

<script> 
function Person(first, last, age, eye) { 
    this.firstName = first; 
    this.lastName = last; 
    this.age = age; 
    this.eyeColor = eye; 
} 
Person.prototype.nationality = "English"; 

var myFather = new Person("John", "Doe", 50, "blue"); 
document.getElementById("demo").innerHTML = 
"My father is " + myFather.nationality; 
</script> 

</body> 
</html> 

了出來放是我的父親是英文

所以JavaScript原型屬性允許你一個dd現有原型的新屬性: JavaScript函數具有原型屬性(此屬性默認爲空),並且當您要實現繼承時在此原型屬性上附加屬性和方法