为什么添加的对象属性不会向下移动?

时间:2016-06-15 07:28:49

标签: javascript

Object.someProp = "hello";
Object.prototype.somProp2 = "hello2";
var i = new Object();
alert(i.somProp2);//1
alert(i.someProp);//2

为什么1可以工作而不是2? 如果几乎每个对象都是从“对象”派生的,那么someProp不应该像someProp2一样遍历链。我是新手,所以任何帮助都很好吗?

1 个答案:

答案 0 :(得分: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>

如果你运行它会告诉你我父亲是英国人未定义的

但如果你运行这个

<!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 prototype属性允许您向现有原型添加新属性:  JavaScript函数有一个prototype属性(默认情况下此属性为空),并且当您要实现继承时,可以在此prototype属性上附加属性和方法