"use strict";
var result = document.getElementById('result');
function Person() {
//STATIC CALL
Person.callfunc();
}
//STATIC PROPERTY
Person.age = 20;
//STATIC METHOD
Person.callfunc = function() {
result.innerHTML += Person.age + "<br>";
};
var obj = new Person();
result.innerHTML += obj.age + "<br>";
<div id='result'></div>
obj无法访问年龄。但是作为父母的孩子应该。我来自Java,刚接触JS。
答案 0 :(得分:0)
使用Object.prototype
怎么样?应该会更好。
"use strict";
var result = document.getElementById('result');
function Person() { }
//STATIC PROPERTY
Person.prototype.age = 20;
var obj = new Person();
result.innerHTML += obj.age + "<br>";
<div id='result'></div>
答案 1 :(得分:0)
Person.age
和Person.prototype.age
之间的区别:
Person.age
age
是函数对象Person()
的属性Person.prototype.age
age
是类对象Person()
的属性请阅读文档: Object.prototype:
通过原型链接,所有对象可以看到更改(所有对象
都可以看到对象原型对象的更改),除非沿着原型链进一步覆盖发生这些更改的属性和方法。这提供了一种非常强大的机制,尽管具有潜在的危险性,它可以覆盖或扩展对象的行为。
function Person()
{
//static call from function object property
Person.callfunc1();
this.weight = 71; //class object property
this.callfunc2 = function()
{
console.log('weight: ', this.weight); // 'weight: 71' because weight is in class object and 'this' is here class object
};
//call from class object property
this.callfunc2();
}
//static property from function object
Person.age = 25;
Person.prototype.name = 'Peter';
//static method from function object
Person.callfunc1 = function()
{
console.log(Person.age); // 25
console.log('weight: ', this.weight); // 'weight: undefined' because weight is in class object, but 'this' is here function object
};
var obj = new Person(); // obj is not a child of Person, this in the instance of it
console.log('obj.age ', obj.age); // 'obj.age undefined' because it is NOT in class object
console.log(obj.name); // 'Peter' because it is in class object
console.log('obj.callfunc1 ', obj.callfunc1); // 'obj.callfunc1 undefined' because it is NOT in class object
console.log(obj.weight); // 71 because it is in class object
答案 2 :(得分:0)
简单地说,实例(在这种情况下为obj)无法通过原型链访问构造函数(在这种情况下为Person)的静态属性和方法。但是,您可以通过.constructor方法访问它们。 因此,以下代码将起作用:
"use strict";
var result = document.getElementById('result');
function Person() {
//STATIC CALL
Person.callfunc();
}
//STATIC PROPERTY
Person.age = 20;
//STATIC METHOD
Person.callfunc = function() {
result.innerHTML += Person.age + "<br>";
};
var obj = new Person();
result.innerHTML += obj.constructor.age + "<br>";
<div id='result'></div>
但是我不知道你为什么要这样做。